Exemple #1
1
  /**
   * Method to find the Euler Tour based on the Hierholzer's algorithm.
   *
   * @param g : Input graph for which the tour is to be found.
   * @return : Returns a list of edges that comprises of the Euler Tour.
   */
  public static List<Edge> findEulerTour(Graph<Vertex> g) {
    Vertex start = g.verts.get(1);
    Stack<Edge> forward = new Stack<Edge>();
    Stack<Edge> backtrack = new Stack<Edge>();
    Edge e = getUnvisitedEdge(start);
    while (e != null) {
      e.visited = true;
      forward.push(e);
      e = getUnvisitedEdge(e.To);
    }

    while (!(forward.isEmpty())) {
      e = forward.pop();
      backtrack.push(e);
      e = getUnvisitedEdge(e.From);
      while (e != null) {
        e.visited = true;
        forward.push(e);
        e = getUnvisitedEdge(e.To);
      }
    }

    List<Edge> path = new LinkedList<Edge>();
    while (!backtrack.isEmpty()) {
      Edge edge = backtrack.pop();
      path.add(edge);
    }
    return path;
  }
 public boolean isValid(String s) {
   if (s == null || s.equals("()") || s.equals("{}") || s.equals("[]")) {
     return true;
   }
   char[] arr = s.toCharArray();
   Stack<Character> stack = new Stack<Character>();
   stack.push(arr[0]);
   for (int i = 1; i < s.length(); i++) {
     if ("({[".indexOf(arr[i] + "") != -1) {
       stack.push(arr[i]);
       continue;
     }
     if (stack.isEmpty()) {
       return false;
     }
     if (arr[i] == ')' && stack.peek() != '(') {
       return false;
     }
     if (arr[i] == '}' && stack.peek() != '{') {
       return false;
     }
     if (arr[i] == ']' && stack.peek() != '[') {
       return false;
     }
     stack.pop();
   }
   if (!stack.isEmpty()) {
     return false;
   }
   return true;
 }
 public boolean isValid(String s) {
   if (s == null || s.length() == 0) {
     return true;
   }
   if (s.length() % 2 != 0) {
     return false;
   }
   Stack<Character> stack = new Stack<Character>();
   for (int i = 0; i < s.length(); i++) {
     Character cur = s.charAt(i);
     if (cur == '(' || cur == '[' || cur == '{') {
       stack.push(cur);
       continue;
     }
     if (cur == ')') {
       if (stack.isEmpty()) return false;
       if (stack.peek() != '(') {
         return false;
       } else stack.pop();
     }
     if (cur == ']') {
       if (stack.isEmpty()) return false;
       if (stack.peek() != '[') {
         return false;
       } else stack.pop();
     }
     if (cur == '}') {
       if (stack.isEmpty()) return false;
       if (stack.peek() != '{') {
         return false;
       } else stack.pop();
     }
   }
   return stack.isEmpty();
 }
 @NotNull
 private static Collection<PsiLanguageInjectionHost> collectInjectionHosts(
     @NotNull PsiFile file, @NotNull TextRange range) {
   Stack<PsiElement> toProcess = new Stack<PsiElement>();
   for (PsiElement e = file.findElementAt(range.getStartOffset());
       e != null;
       e = e.getNextSibling()) {
     if (e.getTextRange().getStartOffset() >= range.getEndOffset()) {
       break;
     }
     toProcess.push(e);
   }
   if (toProcess.isEmpty()) {
     return Collections.emptySet();
   }
   Set<PsiLanguageInjectionHost> result = null;
   while (!toProcess.isEmpty()) {
     PsiElement e = toProcess.pop();
     if (e instanceof PsiLanguageInjectionHost) {
       if (result == null) {
         result = ContainerUtilRt.newHashSet();
       }
       result.add((PsiLanguageInjectionHost) e);
     } else {
       for (PsiElement child = e.getFirstChild(); child != null; child = child.getNextSibling()) {
         if (e.getTextRange().getStartOffset() >= range.getEndOffset()) {
           break;
         }
         toProcess.push(child);
       }
     }
   }
   return result == null ? Collections.<PsiLanguageInjectionHost>emptySet() : result;
 }
  public static boolean isBalanced(String s) {
    Stack<Character> stack = new Stack<Character>();

    for (int i = 0; i < s.length(); ++i) {
      char c = s.charAt(i);
      if (c == '{' || c == '[' || c == '(') stack.push(c);
      else if (c == '}') {
        if (!stack.isEmpty() && stack.peek() == '{') {
          stack.pop();
        } else return false;
      } else if (c == ']') {
        if (!stack.isEmpty() && stack.peek() == '[') {
          stack.pop();
        } else return false;
      } else if (c == ')') {
        if (!stack.isEmpty() && stack.peek() == '(') {
          stack.pop();
        } else return false;
      } else {

      }
    }

    return stack.isEmpty();
  }
Exemple #6
0
  public int maximalRectangle(char[][] matrix) {
    if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;
    int cLen = matrix[0].length; // column length
    int rLen = matrix.length; // row length
    // height array
    int[] h = new int[cLen + 1];
    h[cLen] = 0;
    int max = 0;

    for (int row = 0; row < rLen; row++) {
      Stack<Integer> s = new Stack<Integer>();
      for (int i = 0; i < cLen + 1; i++) {
        if (i < cLen)
          if (matrix[row][i] == '1') h[i] += 1;
          else h[i] = 0;

        if (s.isEmpty() || h[s.peek()] <= h[i]) s.push(i);
        else {
          while (!s.isEmpty() && h[i] < h[s.peek()]) {
            int top = s.pop();
            int area = h[top] * (s.isEmpty() ? i : (i - s.peek() - 1));
            if (area > max) max = area;
          }
          s.push(i);
        }
      }
    }
    return max;
  }
 // Get the front element.
 public int peek() {
   if (stack2.isEmpty()) {
     while (!stack1.isEmpty()) {
       stack2.push(stack1.pop());
     }
   }
   return stack2.peek();
 }
 // Removes the element from in front of queue.
 public void pop() {
   if (stack2.isEmpty()) {
     while (!stack1.isEmpty()) {
       stack2.push(stack1.pop());
     }
   }
   stack2.pop();
 }
 // Get the front element.
 public int peek() {
   if (outStack.isEmpty()) {
     while (!inStack.isEmpty()) {
       int temp = inStack.pop();
       outStack.push(temp);
     }
   }
   return outStack.peek();
 }
 // peek function
 private int peek() {
   if (isEmpty()) return Integer.MIN_VALUE;
   if (stack2.isEmpty()) {
     while (!stack1.isEmpty()) {
       stack2.push(stack1.pop());
     }
   }
   return stack2.peek();
 }
 // Removes the element from in front of queue.
 public void pop() {
   if (outStack.isEmpty()) {
     while (!inStack.isEmpty()) {
       int temp = inStack.pop();
       outStack.push(temp);
     }
   }
   outStack.pop();
 }
 public Stack(Stack<T> stack) {
   Stack<T> tmpStack = new Stack<T>();
   while (!stack.isEmpty()) {
     tmpStack.push(stack.pop());
   }
   while (!tmpStack.isEmpty()) {
     T item = tmpStack.pop();
     push(item);
     stack.push(item);
   }
 }
 // based on the insertion sort
 public static Stack sortStack(Stack s1) {
   Stack s2 = new Stack();
   while (!s1.isEmpty()) {
     int temp = s1.pop();
     while (!s2.isEmpty() && s2.peek() < temp) {
       s1.push(s2.pop());
     }
     s2.push(temp);
   }
   return s2;
 }
Exemple #14
0
  @Override
  public ACTIONS act(StateObservation stateObs, ElapsedCpuTimer elapsedTimer) {

    float avgTime = 10;
    float worstTime = 10;
    float totalTime = 0;
    int numberOfIterations = 0;
    int limitExpansions = 1;

    // ArrayList<Node> queue = new ArrayList<Node>();
    Stack<Node> st = new Stack<Node>();

    Node currentNode = new Node(null, Types.ACTIONS.ACTION_NIL, stateObs);

    st.push(currentNode);

    ArrayList<Types.ACTIONS> possibleActions = stateObs.getAvailableActions();

    while (!st.isEmpty()
        && elapsedTimer.remainingTimeMillis() > 2 * avgTime
        && elapsedTimer.remainingTimeMillis() > worstTime) {
      // while(!st.isEmpty()){
      ElapsedCpuTimer methodTime = new ElapsedCpuTimer();

      currentNode = st.pop();

      if (currentNode.state.getGameWinner() == WINNER.PLAYER_WINS) {
        break;
      }
      if (currentNode.state.getGameWinner() == WINNER.PLAYER_LOSES) {
        continue;
      }

      if (deepFromRoot(currentNode) <= limitExpansions - 1) {
        possibleActions = currentNode.state.getAvailableActions();
        for (int i = 0; i < possibleActions.size(); i++) {
          StateObservation newState = currentNode.state.copy();
          newState.advance(possibleActions.get(i));
          Node newNode = new Node(currentNode, possibleActions.get(i), newState);
          st.push(newNode);
        }
      }
      if (st.isEmpty()) {
        limitExpansions += 1;
        st.push(new Node(null, Types.ACTIONS.ACTION_NIL, stateObs));
      }

      numberOfIterations += 1;
      totalTime += methodTime.elapsedMillis();
      avgTime = totalTime / numberOfIterations;
    }
    // System.out.println(numberOfIterations);
    return currentNode.getAction();
  }
Exemple #15
0
  @Test
  public void testPush() {
    // Stack stack = new Stack(5);
    Integer i = 0;
    stack.push(i);
    assertFalse("Stack size = 1", stack.isEmpty());

    Stack<Double> stackDouble = new Stack<Double>();
    Double f = 0.1;
    stackDouble.push(f);
    assertFalse("Stack size = 1", stackDouble.isEmpty());
  }
Exemple #16
0
  @Test
  public void testEmpty() {
    Stack<String> testStack = new Stack<String>();
    assertTrue(testStack.isEmpty());

    String test = "Test";
    testStack.push(test);
    assertFalse(testStack.isEmpty());

    testStack.pop();
    assertTrue(testStack.isEmpty());
  }
 /**
  * Solution idea:
  *
  * <p>When traverse the stack and move it to the sorted stack, we can use a variable to store the
  * minimum element and then push it to the top of the stack.
  */
 public Stack sort(Stack stack) {
   Stack result = new Stack();
   if (stack != null) {
     while (!stack.isEmpty()) {
       int item = stack.pop();
       while (!result.isEmpty() && result.peek() < item) {
         stack.push(result.pop());
       }
       result.push(item);
     }
   }
   return result;
 }
  public static void main(String[] args) throws IOException {
    br = new BufferedReader(new InputStreamReader(System.in));
    out = new PrintWriter(new OutputStreamWriter(System.out));
    // br = new BufferedReader(new FileReader("in.txt"));
    // out = new PrintWriter(new FileWriter("out.txt"));

    N = readInt();

    val = new int[N];
    hi = new int[N];
    lo = new int[N];
    poss = new ArrayList<ArrayList<Integer>>();
    intervals = new TreeSet<Interval>();

    for (int i = 0; i < N; i++) val[i] = readInt();

    for (int i = 0; i < 2 * N; i++) poss.add(new ArrayList<Integer>());

    Stack<State> s = new Stack<State>();

    // processing upper bound (first number less than the current number)
    for (int i = N - 1; i >= 0; i--) {
      while (!s.isEmpty() && val[i] < s.peek().val) s.pop();
      if (s.isEmpty()) hi[val[i]] = N;
      else hi[val[i]] = s.peek().index;
      s.push(new State(val[i], i));
    }

    s.clear();
    // processing lower bound (last number greater than the current number)
    for (int i = 0; i < N; i++) {
      while (!s.isEmpty() && val[i] > s.peek().val) s.pop();
      if (s.empty()) lo[val[i]] = -1;
      else lo[val[i]] = s.peek().index;
      s.push(new State(val[i], i));
    }

    for (int i = 0; i < N; i++) {
      int diff = val[i] - i + N - 1;
      poss.get(diff).add(i);
    }

    for (int i = 0; i < 2 * N; i++) {
      sweep(poss.get(i));
    }

    out.println(intervals.size());
    for (Interval i : intervals) out.printf("%d %d\n", i.l + 1, i.r + 1);

    out.close();
  }
  /**
   * 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;
  }
Exemple #20
0
 @Test
 public void PushNull() {
   // Stack stack = new Stack(2);
   Integer i = null;
   stack.push(i);
   assertFalse("Stack size = 1", stack.isEmpty());
 }
Exemple #21
0
 @Test
 public void testPushPop() {
   // Stack stack = new Stack(5);
   stack.push(0);
   stack.pop();
   assertTrue("Stack is empty", stack.isEmpty());
 }
  /**
   * find a solution to the initial board (using the A* algorithm). Result will be stored in
   * searchNodeSolution queue;
   *
   * @param initial
   */
  public Solver(Board initial) {
    SearchNode initSearchNd = new SearchNode(initial, null);
    initialBoard = initial;
    pq.insert(initSearchNd);

    // output
    System.out.println("======Original SearchBoard==========");
    outputSN(initSearchNd);

    // find the Goal SearchNode
    while (!pq.min().board.isGoal()) {
      Stack<SearchNode> stackSNforNbrs = new Stack<SearchNode>();
      System.out.println("======NextLevel SearchBoard==========");

      // Insert all neighbors in the priority queue
      stackSNforNbrs = findNbrSearchNode(pq.delMin());
      while (stackSNforNbrs.size() != 0) {
        pq.insert(stackSNforNbrs.pop());
      }
    }

    // Trace back the search node
    SearchNode snInSolution = pq.min();
    Stack<SearchNode> stacksolution = new Stack<SearchNode>();
    while (snInSolution.prevNode != null) {
      stacksolution.push(snInSolution);
      snInSolution = snInSolution.prevNode;
    }
    stacksolution.push(initSearchNd);

    // Make it reverse order
    while (!stacksolution.isEmpty()) searchNodeSolution.enqueue(stacksolution.pop());
  }
 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);
       }
     }
   }
 }
Exemple #24
0
 public XNStackFrame getCurrentStackFrame() {
   if (!callStack.isEmpty()) {
     return callStack.peek();
   } else {
     return null;
   }
 }
Exemple #25
0
 public XNResponder getCurrentResponder() {
   if (!responderStack.isEmpty()) {
     return responderStack.peek();
   } else {
     return null;
   }
 }
Exemple #26
0
  private CellSet seedFillOld(Cell seed, char newChar) {
    CellSet cellsFilled = new CellSet();
    char oldChar = get(seed);

    if (oldChar == newChar) return cellsFilled;
    if (isOutOfBounds(seed)) return cellsFilled;

    Stack<Cell> stack = new Stack<Cell>();

    stack.push(seed);

    while (!stack.isEmpty()) {
      Cell cell = stack.pop();

      set(cell, newChar);
      cellsFilled.add(cell);

      Cell nCell = cell.getNorth();
      Cell sCell = cell.getSouth();
      Cell eCell = cell.getEast();
      Cell wCell = cell.getWest();

      if (get(nCell) == oldChar) stack.push(nCell);
      if (get(sCell) == oldChar) stack.push(sCell);
      if (get(eCell) == oldChar) stack.push(eCell);
      if (get(wCell) == oldChar) stack.push(wCell);
    }

    return cellsFilled;
  }
  @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;
  }
Exemple #28
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);
       }
     }
   }
 }
Exemple #29
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);
 }
 public int largestRectangleArea(int[] height) {
   int n = height.length;
   Stack<Integer> stack = new Stack<Integer>();
   int max = 0;
   for (int i = 0; i <= n; i++) {
     int curt = (i == n) ? -1 : height[i];
     while (!stack.isEmpty() && curt < height[stack.peek()]) {
       int index = stack.pop();
       int left = (stack.isEmpty()) ? -1 : stack.peek();
       int right = i;
       max = Math.max(max, height[index] * (right - left - 1));
     }
     stack.push(i);
   }
   return max;
 }