Example #1
1
  public static void main(String[] args) {
    // String output;
    Ball BigBall = new Ball(5);
    JFrame frame1 = new JFrame();
    frame1.setTitle("Welcome to Ship!");
    frame1.setSize(300, 300);
    frame1.setLocation(200, 100);
    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JComboBox<String> box = new JComboBox<String>(new String[] {"Casey", "Connolly", "Nielson"});
    JPanel panel = new JPanel();
    panel.add(box);
    frame1.add(panel);
    frame1.setVisible(true);

    TV tv1 = new TV();
    tv1.turnOn();
    tv1.setChannel(30);
    tv1.setVolume(3);

    System.out.println(tv1.toString());
    Stack stacker = new Stack();

    for (int i = 0; i < 10; i++) stacker.push(i);
    while (!stacker.empty()) System.out.println(stacker.pop() + " ");

    System.out.println(BigBall.toString());
    System.out.println("Finished");
  }
  public StringBuffer translate() {
    for (index = 0; index < line.length(); index++) {
      char c = line.charAt(index);

      if (Character.isDigit(c)) {
        dealWithOperand();
      } else if (isOperator(c)) {
        dealWithOperator(c);
      } else if (c == '(') {
        stack.push(new Character(c));
      } else if (c == ')') {
        dealWithCloser();
      } else if (Character.isSpaceChar(c)) {
        // do nothing
      } else {
        System.out.println("Error: unknown character" + c);
      }
    }

    // pop and output all the operators left on the stack
    while (!stack.empty()) {
      out.append(popChar());
    }
    return out;
  }
Example #3
0
  public void reorderList(ListNode head) {
    if (head == null || head.next == null || head.next.next == null) {
      return;
    }
    ListNode oneStep = head;
    ListNode twoStep = head;

    while (twoStep != null && twoStep.next != null) {
      twoStep = twoStep.next.next;
      oneStep = oneStep.next;
    }

    ListNode half = oneStep.next;
    oneStep.next = null;

    Stack<ListNode> stack = new Stack<ListNode>();
    while (half != null) {
      stack.push(half);
      half = half.next;
    }

    ListNode tmp = head;

    while (head != null) {
      ListNode oldRight = head.next;
      if (stack.empty()) {
        break;
      }
      head.next = stack.pop();
      head.next.next = oldRight;
      head = oldRight;
    }
    head = tmp;
  }
Example #4
0
  /**
   * Get the ISchemaElement corresponding to this IDocumentElementNode
   *
   * @param node
   * @param extensionPoint the extension point of the schema, if <code>null</code> it will be
   *     deduced
   * @return the ISchemaElement for <code>node</code>
   */
  public static ISchemaElement getSchemaElement(IDocumentElementNode node, String extensionPoint) {
    if (extensionPoint == null) {
      IMonitorObject obj = getTopLevelParent(node);
      if (!(obj instanceof IMonitorExtension)) return null;
      extensionPoint = ((IMonitorExtension) obj).getPoint();
    }
    ISchema schema = MDECore.getDefault().getSchemaRegistry().getSchema(extensionPoint);
    if (schema == null) return null;

    // Bug 213457 - look up elements based on the schema in which the parent is found
    if (schema.getIncludes().length == 0 || "extension".equals(node.getXMLTagName())) // $NON-NLS-1$
    return schema.findElement(node.getXMLTagName());

    // if element is not "extension" & has multiple sub-schemas,
    // Then search for the element in the same schema in which the parent element if found.
    Stack stack = new Stack();
    while (node != null) {
      String tagName = node.getXMLTagName();
      if ("extension".equals(tagName)) // $NON-NLS-1$
      break;
      stack.push(node.getXMLTagName());
      node = node.getParentNode();
    }
    ISchemaElement element = null;
    while (!stack.isEmpty()) {
      element = schema.findElement((String) stack.pop());
      if (element == null) return null;
      schema = element.getSchema();
    }
    return element;
  }
Example #5
0
  public static boolean isPalindrome(Node n) {
    Node slow = n;
    Node fast = n;
    Stack<Integer> stack = new Stack<Integer>();

    while (fast != null && fast.next != null) {
      stack.push(slow.data);
      slow = slow.next;
      fast = fast.next.next;
    }

    // odd number, skip the middle one
    if (fast != null) {
      slow = slow.next;
    }

    while (!stack.empty()) {
      int top = stack.pop();
      if (slow.data != top) {
        return false;
      }
      slow = slow.next;
    }
    return true;
  }
Example #6
0
 public void parseStyleDeclaration(CSSStyleDeclaration sd, InputSource source) throws IOException {
   Stack nodeStack = new Stack();
   nodeStack.push(sd);
   CSSOMHandler handler = new CSSOMHandler(nodeStack);
   _parser.setDocumentHandler(handler);
   _parser.parseStyleDeclaration(source);
 }
Example #7
0
 public boolean visit(Assignment assignment) throws Exception {
   Expression left = assignment.getVariable();
   if (left instanceof FieldAccess) { // class variable ($this->a = .)
     FieldAccess fieldAccess = (FieldAccess) left;
     Expression dispatcher = fieldAccess.getDispatcher();
     if (dispatcher instanceof VariableReference
         && "$this".equals(((VariableReference) dispatcher).getName())) { // $NON-NLS-1$
       Expression field = fieldAccess.getField();
       if (field instanceof SimpleReference) {
         SimpleReference var = (SimpleReference) field;
         int modifiers = Modifiers.AccPublic;
         int offset = var.sourceStart();
         int length = var.sourceEnd() - offset;
         StringBuilder metadata = new StringBuilder();
         if (fCurrentQualifier != null) {
           metadata.append(fCurrentQualifierCounts.get(fCurrentQualifier));
           metadata.append(";"); // $NON-NLS-1$
         }
         modifyDeclaration(
             assignment,
             new DeclarationInfo(
                 IModelElement.FIELD,
                 modifiers,
                 offset,
                 length,
                 offset,
                 length,
                 '$' + var.getName(),
                 metadata.length() == 0 ? null : metadata.toString(),
                 null,
                 fCurrentQualifier,
                 fCurrentParent));
       }
     }
   } else if (left instanceof VariableReference) {
     int modifiers = Modifiers.AccPublic | Modifiers.AccGlobal;
     if (!declarations.empty()
         && declarations.peek() instanceof MethodDeclaration
         && !methodGlobalVars.peek().contains(((VariableReference) left).getName())) {
       return visitGeneral(assignment);
     }
     int offset = left.sourceStart();
     int length = left.sourceEnd() - offset;
     modifyDeclaration(
         assignment,
         new DeclarationInfo(
             IModelElement.FIELD,
             modifiers,
             offset,
             length,
             offset,
             length,
             ((VariableReference) left).getName(),
             null,
             null,
             null,
             null));
   }
   return visitGeneral(assignment);
 }
Example #8
0
  // check that algorithm computes either the topological order or finds a directed cycle
  private void dfs(Digraph G, int v) {
    onStack[v] = true;
    marked[v] = true;
    for (int w : G.adj(v)) {

      // short circuit if directed cycle found
      if (cycle != null) return;

      // found new vertex, so recur
      else if (!marked[w]) {
        edgeTo[w] = v;
        dfs(G, w);
      }

      // trace back directed cycle
      else if (onStack[w]) {
        cycle = new Stack<Integer>();
        for (int x = v; x != w; x = edgeTo[x]) {
          cycle.push(x);
        }
        cycle.push(w);
        cycle.push(v);
      }
    }

    onStack[v] = false;
  }
Example #9
0
 /**
  * Returns a path between the source vertex <tt>s</tt> and vertex <tt>v</tt>, or <tt>null</tt> if
  * no such path.
  *
  * @param v the vertex
  * @return the sequence of vertices on a path between the source vertex <tt>s</tt> and vertex
  *     <tt>v</tt>, as an Iterable
  */
 public Iterable<Integer> pathTo(int v) {
   if (!hasPathTo(v)) return null;
   Stack<Integer> path = new Stack<Integer>();
   for (int x = v; x != s; x = edgeTo[x]) path.push(x);
   path.push(s);
   return path;
 }
 public Node peek() {
   if (s2 == null) s2 = new Stack();
   if (s2.peek() == null) {
     transfer();
   }
   return s2.peek();
 }
 public int poll() {
   if (s2 == null) s2 = new Stack();
   if (s2.peek() == null) {
     transfer();
   }
   return s2.pop();
 }
Example #12
0
 public XNStackFrame getCurrentStackFrame() {
   if (!callStack.isEmpty()) {
     return callStack.peek();
   } else {
     return null;
   }
 }
Example #13
0
 public XNResponder getCurrentResponder() {
   if (!responderStack.isEmpty()) {
     return responderStack.peek();
   } else {
     return null;
   }
 }
Example #14
0
 private void initStack(XNContext parent) {
   initStack();
   firstResponder = parent.firstResponder;
   responderStack.addAll(parent.responderStack);
   callStack.addAll(parent.callStack);
   result = parent.result;
 }
Example #15
0
 /**
  * Adds a new cell to the table with the specified actors in a {@link Stack}.
  *
  * @param actors May be null to add a stack without any actors.
  */
 public Cell stack(Actor... actors) {
   Stack stack = new Stack();
   if (actors != null) {
     for (int i = 0, n = actors.length; i < n; i++) stack.addActor(actors[i]);
   }
   return add(stack);
 }
Example #16
0
	private void dfs(Digraph G ,int v){
		onStack[v] = true ; 
		marked[v] = true ; 
		for(int w:G.adj(v)) 

		if(this.hasCycle()) {

		}
		if(!marked[v]){
				edgeTo[w] = v;
				dfs(G,w);
			}
		else{
			if(onStack[w]){
				cycle = new Stack<Integer>();
				for(int x = v; x!=w;x =edgeTo[x]) cycle.push(x);
				cycle.push(w);
				cycle.push(v);
			}
		} 

		onStack[v] = false;

		
	}
Example #17
0
  public void buildTree() {
    Stack<NodeStack> stack = new Stack<NodeStack>();
    Block curr = firstData;
    Node root = null;
    long low = 0;

    while (curr != null) {
      root = curr;
      int level = 0;
      low = curr.keys[0];
      while (stack.peek().level == level) {
        NodeStack lhsNode = stack.pop();
        root = new InnerNode(low, lhsNode.node, root);
        low = lhsNode.low;
        level++;
      }
      curr = curr.next;
    }
    if (root != null) {
      while (!stack.empty()) {
        NodeStack lhsNode = stack.pop();
        root = new InnerNode(low, lhsNode.node, root);
        low = lhsNode.low;
      }
    }
  }
Example #18
0
 /** main method for solver. solves a sudoku puzzle */
 public static void main(String[] args) {
   Stack<GameBoard> stack = new LinkedList<GameBoard>(); // intializes stack
   GameBoard board = new GameBoard(); // creates the game board
   stack.push(board);
   boolean solved = false;
   while (solved == false) {
     if (stack.isEmpty()) // if stack is empty the board is unsolvable
     System.out.println("board is unsolvable");
     GameBoard curr = stack.pop();
     if (curr.solved()) {
       System.out.println(curr);
       solved = true;
       return;
     }
     int[] mostConstrained =
         curr
             .mostConstrained(); // array containing the row and column of the most constrined spot
                                 // on the board
     for (int i = 1; i < 10; i++) // checks what numbers can be placed at the most constrained spot
     {
       if (curr.canPlace(mostConstrained[0], mostConstrained[1], i)) {
         GameBoard temp =
             new GameBoard(
                 curr); // calls the copy constructor and creates a copy of current game board
         temp.place(mostConstrained[0], mostConstrained[1], i);
         stack.push(temp);
       }
     }
   }
 }
Example #19
0
  public boolean visit(CallExpression call) throws Exception {
    FieldDeclaration constantDecl = ASTUtils.getConstantDeclaration(call);
    if (constantDecl != null) {
      // In case we are entering a nested element
      if (!declarations.empty() && declarations.peek() instanceof MethodDeclaration) {
        deferredDeclarations.add(constantDecl);
        return visitGeneral(call);
      }

      visit((FieldDeclaration) constantDecl);

    } else {
      int argsCount = 0;
      CallArgumentsList args = call.getArgs();
      if (args != null && args.getChilds() != null) {
        argsCount = args.getChilds().size();
      }

      modifyReference(
          call,
          new ReferenceInfo(
              IModelElement.METHOD,
              call.sourceStart(),
              call.sourceEnd() - call.sourceStart(),
              call.getName(),
              Integer.toString(argsCount),
              null));
    }

    return visitGeneral(call);
  }
Example #20
0
 @Override
 public void run() {
   for (int i = 0; i <= 9; i++) {
     stack.push(i);
     System.out.println("Pushed " + i + ". Currently: " + (stack.getLast() + 1));
   }
 }
Example #21
0
 private void setBeanProperty(String name, Object object) {
   Bean parentBean = null;
   if (beansStack.size() > 0) {
     parentBean = (Bean) beansStack.peek();
     parentBean.setProperty(name, object);
   }
 }
Example #22
0
 public List<Interval> merge(List<Interval> intervals) {
   if (intervals == null) return null;
   Collections.sort(intervals, new IntervalComparator());
   Stack<Interval> stack = new Stack<Interval>();
   for (Interval i : intervals) {
     if (stack.isEmpty()) {
       stack.push(i);
     } else {
       Interval t = stack.peek();
       if (hasOverlap(t, i)) {
         Interval newInterval = new Interval(t.start, Math.max(t.end, i.end));
         stack.pop();
         stack.push(newInterval);
       } else {
         stack.push(i);
       }
     }
   }
   int length = stack.size() - 1;
   Interval[] intervalArray = new Interval[stack.size()];
   for (int i = length; i >= 0; i--) {
     intervalArray[i] = stack.pop();
   }
   return Arrays.asList(intervalArray);
 }
Example #23
0
  public void printSolution() {
    String currState = "www0bbb";
    File file = new File("solution_slidingtile_dfs.txt");
    try {
      FileWriter fw = new FileWriter(file);
      path.push(currState);
      while (parentMap.get(currState) != null) {
        // System.out.println("inside while, parentMap.get(currState)!=null");
        path.push(parentMap.get(currState));
        currState = parentMap.get(currState);
      }
      System.out.println("Solution path:");

      while (!path.empty()) {
        // System.out.println("inside while, stack not empty");
        // System.out.println(path.pop());
        fw.write(path.pop());
        fw.write("\n");
      }
      fw.close();
    } catch (IOException ie) {
      ie.printStackTrace();
    } finally {

    }
  }
Example #24
0
  /** Create a random Json document with random values */
  public String getRandomJson(int nbNodes) {
    // init
    sb.setLength(0);
    sb.append("{");
    states.clear();
    states.add(OBJECT_ATT);
    images.clear();
    nodes.clear();
    incr.clear();
    datatypes.clear();
    types.clear();
    curNodePath.length = 1;
    curNodePath.offset = 0;
    Arrays.fill(curNodePath.ints, -1);
    shouldFail = false;
    nestedObjs = 0;

    // <= so that when nbNodes == 1, the json is still valid
    /*
     * the generated json might be uncomplete, if states is not empty, and
     * the maximum number of nodes has been reached.
     */
    for (final int i = 0; i <= nbNodes && !states.empty(); nbNodes++) {
      sb.append(this.getWhitespace()).append(this.getNextNode()).append(this.getWhitespace());
    }
    shouldFail = shouldFail ? true : !states.empty();
    return sb.toString();
  }
Example #25
0
 /**
  * Tests whether this handler has completed parsing a geometry. If this is the case, {@link
  * #getGeometry()} can be called to get the value of the parsed geometry.
  *
  * @return if the parsing of the geometry is complete
  */
 public boolean isGeometryComplete() {
   if (stack.size() > 1) return false;
   // top level node on stack needs to have at least one child
   Handler h = (Handler) stack.peek();
   if (h.children.size() < 1) return false;
   return true;
 }
  @Override
  public List<String> getPaths(int catId) {
    int depth = getDepth(catId);
    List<Stack<Integer>> idPaths = new LinkedList<>();
    Stack<Integer> stack = new Stack<>();
    stack.add(catId);
    idPaths.add(stack);

    for (int i = depth; i > 1; i--) {
      idPaths = walkUp(idPaths);
    }

    // idPaths里面的每条Path都是存放在栈中的以id表示的路径,下面转换为字符串形式
    List<String> list = new LinkedList<>();
    for (Stack<Integer> path : idPaths) {
      StringBuilder sb = new StringBuilder();
      while (!path.isEmpty()) {
        int id = path.pop();
        String name = getNameById(id);
        int conceptCount = getConceptCount(id);
        sb.append("/").append(name + "(" + conceptCount + ")");
      }
      list.add(sb.toString());
    }
    return list;
  }
Example #27
0
  public static boolean umpadi(Stack s) {
    byte[] topElmt = ((Entry) s.peek()).getPart();
    byte[] oldTopElmt = topElmt;

    if (ByteMeth.endsWith(topElmt, Constant.umpadi)) {
      // clia.unl.unicode.utils.Utils.printOut(Analyser.print, x + "umpadi");
      s.pop();
      s.push(new Entry(Constant.pati, Tag.ParticleSuffix));
      s.push(new Entry(Constant.um, Tag.ThirdFutureNeuterSingularORRP));
      topElmt = ByteMeth.subArray(topElmt, 0, topElmt.length - Constant.umpadi.length);
      if (ByteMeth.isEqual(topElmt, Constant.kEtk)) {
        topElmt = ByteMeth.replace(topElmt, Constant.L, 2);
      }
      if (ByteMeth.endsWith(topElmt, Constant.var) || ByteMeth.endsWith(topElmt, Constant.thar)) {
        topElmt = ByteMeth.replace(topElmt, Constant.A, Constant.ar.length);
      }
      if (ByteMeth.isEqual(topElmt, Constant.kaRk)
          || ByteMeth.isEqual(topElmt, Constant.viRk)
          || ByteMeth.isEqual(topElmt, Constant.n_iRk)) {
        topElmt = ByteMeth.replace(topElmt, Constant.l, 2);
      }
      if (ByteMeth.isEqual(topElmt, Constant.sAk) || ByteMeth.isEqual(topElmt, Constant.pOk)) {
        topElmt = ByteMeth.subArray(topElmt, 0, topElmt.length - 1);
      }
      s.push(new Entry(topElmt, -1, oldTopElmt));
      Sandhi.kk(s);
      Sandhi.check(s);
      return true;
    }

    return false;
  }
  private static void MetodosPilas(Stack<String> pila) {
    System.out.println("¿Qué desea hacer?");
    System.out.println(
        "1- Ver la pila\n2- Agregar elemento\n3- Quitar elemento\n4- Ver tamaño\n5- Salir");
    Scanner opcion = new Scanner(System.in);
    switch (opcion.nextInt()) {
      case 1:
        System.out.println("Contenido de la pila: " + pila);
        MetodosPilas(pila);
        break;

      case 2:
        System.out.println("Escriba el numero que desee agregar a la pila:");
        Scanner addpila = new Scanner(System.in);
        pila.push(addpila.next());
        System.out.println("El contenido de la pila ahora es: " + pila);
        System.out.println("El elemento se agregó al inicio de la lista");
        MetodosPilas(pila);
        break;

      case 3:
        System.out.println("Se eliminó el último elemento de la lista: " + pila.pop());
        System.out.println("Ahora el contenido de la pila es: " + pila);
        MetodosPilas(pila);
        break;

      case 4:
        System.out.println("El tamaño de la pila es: " + pila.size());
        MetodosPilas(pila);
        break;

      default:
        break;
    }
  }
Example #29
0
  // check that algorithm computes either the topological order or finds a directed cycle
  private void dfs(EdgeWeightedDigraph G, int v) {
    onStack[v] = true;
    marked[v] = true;
    for (DirectedEdge e : G.adj(v)) {
      int w = e.to();

      // short circuit if directed cycle found
      if (cycle != null) return;

      // found new vertex, so recur
      else if (!marked[w]) {
        edgeTo[w] = e;
        dfs(G, w);
      }

      // trace back directed cycle
      else if (onStack[w]) {
        cycle = new Stack<DirectedEdge>();
        while (e.from() != w) {
          cycle.push(e);
          e = edgeTo[e.from()];
        }
        cycle.push(e);
      }
    }

    onStack[v] = false;
  }
Example #30
0
 public static void createNgramsFromFolder(
     File input_folder, File output_folder, int ngram_value) {
   Stack<File> stack = new Stack<File>();
   stack.push(input_folder);
   while (!stack.isEmpty()) {
     File child = stack.pop();
     if (child.isDirectory()) {
       for (File f : child.listFiles()) stack.push(f);
     } else if (child.isFile()) {
       try {
         System.out.println("Processing: " + child.getAbsolutePath());
         FileReader fr = new FileReader(child.getAbsolutePath());
         FileWriter outputFile = new FileWriter(output_folder + "/file" + file_no);
         BufferedReader br = new BufferedReader(fr);
         String readline = "";
         while ((readline = br.readLine()) != null) {
           String[] words = readline.split("\\s+");
           for (int i = 0; i < words.length - ngram_value + 1; i++) {
             String ngram = "";
             for (int j = 0; j < ngram_value; j++) ngram = ngram + " " + words[i + j];
             outputFile.write(ngram + "\n");
           }
         }
         file_no++;
         outputFile.close();
         br.close();
         fr.close();
       } catch (Exception e) {
         System.out.println("File not found:" + e);
       }
     }
   }
 }