/** * 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; }
/*\ * Helper method for evaluate. Takes as input the user generated expression, and tests it to make sure that * , at least in terms of brackets, it is a well formed expression. Method tests for: * ->Bracket matching. Every open bracket must have a closing bracket * ->Integer values and arithmatic operators inside brackets. An expression such as 3+() would be considered malformed. * Method returns boolean value true if expression is well formed, and false otherwise \*/ static boolean bracketMatch(String expression) throws Exception { Stack<Character> bracketSum = new Stack<Character>(); // This stack will keep track of brackets which are yet to be closed for (int i = 0; i < expression.length() - 1; i++) { if (expression.charAt(i) == '(') { // Check for empty sets of brackets if (expression.charAt(i + 1) == ')') { return false; } Character openBrac = new Character(expression.charAt(i)); bracketSum.push(openBrac); // Add open bracket to total } else if (expression.charAt(i) == ')') { /*\ Two cases covered here. Either we have a closing bracket where there should not be one, in which case * an EmptyStackException is thrown, or else we have closed an open bracket, in which case we * remove a bracket from bracketSun \*/ bracketSum.pop(); } } // Check last character in expression. if (expression.charAt(expression.length() - 1) == '(') return false; else if (expression.charAt(expression.length() - 1) == ')') { bracketSum.pop(); } // Check to see if all brackets closed else if (!bracketSum.empty()) { return false; } return true; }
public static boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') stack.push(s.charAt(i)); else if (s.charAt(i) == ')' && !stack.empty() && stack.peek() == '(') stack.pop(); else if (s.charAt(i) == ']' && !stack.empty() && stack.peek() == '[') stack.pop(); else if (s.charAt(i) == '}' && !stack.empty() && stack.peek() == '{') stack.pop(); else return false; } return stack.empty(); }
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(); }
private static long computeExpression(Stack<Long> oper, String op) { if (oper.empty()) return -1; long oper1 = oper.pop(); if (oper.empty()) return -1; long oper2 = oper.pop(); if ("*".equals(op)) { return oper1 * oper2; } else { long result = 1; for (long i = 0; i < oper1; i++) { result *= oper2; } return result; } }
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); } } } }
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; }
/** * Does not produce FN. To be fixed soon. * * <p>Array is constuceted as: * * <p>arr[0] = TP arr[1] = FP arr[2] = TN arr[3] = FN * * @param pred * @param ht * @return */ public static double[] parsePredicted(String pred, Map<String, StringBuilder> ht) { if (pred == null || !pred.matches("[(.)]+") || ht == null) return null; double[] arr = new double[] {0, 0, 0, 0}; Stack<Integer> stk = new Stack<Integer>(); for (int i = 0; i < pred.length(); i++) { if (pred.charAt(i) == '(') stk.push(i); else if (pred.charAt(i) == ')') { String bp = stk.pop() + ":" + i; StringBuilder sb = ht.get(bp); if (sb == null) ht.put(bp, new StringBuilder("P")); else sb.append("P"); } } for (Entry<String, StringBuilder> me : ht.entrySet()) { String s = me.getValue().toString(); String bp = me.getKey(); // TP if (s.length() == 2) arr[0]++; // FN else if (s.contains("O")) arr[3]++; // FP else if (s.contains("P")) arr[1]++; // calculate all possible base pairs? // TN...? } return arr; }
static void test00() { Aron.beg(); PriorityQueue<Interval> queue = new PriorityQueue<Interval>(); Stack<Interval> stack = new Stack<Interval>(); int[] arr1 = {4, 1, 2, 6, 9}; int[] arr2 = {5, 1, 4, 9, 10}; for (int i = 0; i < arr1.length; i++) { queue.add(new Interval(arr1[i], arr2[i])); } if (queue.size() > 0) { stack.push(queue.remove()); } while (!queue.isEmpty()) { Interval top = stack.peek(); Interval inter = queue.remove(); if (top.end < inter.begin) stack.push(inter); else { stack.peek().end = Math.max(stack.peek().end, inter.end); } } while (!stack.empty()) { System.out.println("[" + stack.peek().begin + " " + stack.peek().end + "]"); stack.pop(); } Aron.end(); }
private Runner getRunner() { try { return (Runner) threadpool.pop(); } catch (EmptyStackException empty) { if (runners.activeCount() > 255) throw new RuntimeException("System overload"); return new Runner(); } }
private static long evaluateExpression(String expr) { Stack<Long> oper = new Stack<Long>(); Stack<String> op = new Stack<String>(); int i = 0; while (i < expr.length()) { char ch = expr.charAt(i); if (ch >= '0' && ch <= '9') { StringBuffer sb = new StringBuffer(); sb.append(ch); while (++i < expr.length()) { ch = expr.charAt(i); if (ch >= '0' && ch <= '9') { sb.append(ch); } else { break; } } oper.push(Long.parseLong(sb.toString())); if (!op.empty() && ("**".equals(op.peek()))) { oper.push(computeExpression(oper, op.pop())); } if (i == expr.length()) { while (!op.empty() && "*".equals(op.peek())) { oper.push(computeExpression(oper, op.pop())); } } } else if (ch == '*') { StringBuffer sb = new StringBuffer(); sb.append(ch); while (++i < expr.length()) { ch = expr.charAt(i); if (ch == '*') { sb.append(ch); } else { break; } } if (sb.length() > 2) { return -1; } op.push(sb.toString()); } } if (!op.empty() || oper.empty()) return -1; return oper.pop(); }
public synchronized void workAllJobs() { while (!jobs.isEmpty()) { loadJob(jobs.remove()); } while (!shadertoset.empty()) { shadertoset.pop().load(); } }
public DictionaryEntryInterpreter newEntryInterpreter() { synchronized (interpreterPool) { if (!interpreterPool.empty()) { return (DictionaryEntryInterpreter) interpreterPool.pop(); } } return new DictionaryEntryInterpreter(this); }
/* This method evaluates the given arithmetic expression and returns * its Integer value. The method throws an Exception if the expression * is malformed.*/ static Integer evaluate(String expr) throws Exception { StringTokenizer st = new StringTokenizer(expr, delimiters, true); Stack<Integer> intArgs = new Stack<Integer>(); Stack<String> delimiterArgs = new Stack<String>(); if (!bracketMatch(expr)) { throw new Exception(); // Malformed expression given as input, throw exception } /*Fill the integer and delimiter argument stacks with tokens from input string*/ while (st.hasMoreTokens()) { String token = st.nextToken(); // Store current token for sorting if (token.equals(")")) { /*\ Do not add bracket to delimiterArgs, stripping it from expression. Instead, take contents of brackets * and perform specified operation on them \*/ Integer product = performOperation(intArgs.pop(), intArgs.pop(), delimiterArgs.pop()); intArgs.push(product); } else if (token.equals("(")) ; // Do nothing in this case. This strips the bracket from the expression else if (isInt(token)) { // Store the integer in the stack intArgs.push(Integer.parseInt(token)); } else { // Store the operator delimiterArgs.push(token); } } /*Evaluate the simplified expression contained in our stacks*/ while (!(delimiterArgs.empty())) { Integer product = performOperation(intArgs.pop(), intArgs.pop(), delimiterArgs.pop()); intArgs.push(product); } return intArgs.pop(); } // end of evaluate
public DirectoryDescendingFileFinderImpl(File root, FilenameFilter filter, boolean canonical) throws IOException { if (!root.isDirectory()) throw new IllegalArgumentException(root.getName() + " is not a directory."); this.filter = filter; this.canonical = canonical; blossomDirectory(root); while (files.empty() && !direx.empty()) blossomDirectory((File) direx.pop()); }
public static void divide(Stack<Integer> l) { try { int x = l.pop(); int y = l.pop(); l.push(x / y); } catch (StackEmptyException e) { error(); } }
public static void multiply(Stack<Integer> l) { try { int x = l.pop(); int y = l.pop(); l.push(x * y); } catch (StackEmptyException e) { error(); } }
public static void subtract(Stack<Integer> l) { try { int x = l.pop(); int y = l.pop(); l.push(x - y); } catch (StackEmptyException e) { error(); } }
public static void main(String[] args) { Stack s = new Stack(args.length); for (int i = 0; i < args.length; i++) { s.push(args[i]); } for (int j = 0; j < args.length; j++) { System.out.println(s.pop()); } }
public static Map<String, StringBuilder> parseNative(String nat) { if (nat == null || !nat.matches("[(.)]+")) return null; Stack<Integer> stk = new Stack<Integer>(); Map<String, StringBuilder> ht = new HashMap<String, StringBuilder>(); for (int i = 0; i < nat.length(); i++) { if (nat.charAt(i) == '(') stk.push(i); else if (nat.charAt(i) == ')') ht.put(stk.pop() + ":" + i, new StringBuilder("O")); } return ht; }
public TokenizedInputDictionaryExtension newTokenizedInputExtension(DefaultTokenizedInput input) { synchronized (tokenizedInputExtensionPool) { if (!tokenizedInputExtensionPool.empty()) { TokenizedInputDictionaryExtension result = (TokenizedInputDictionaryExtension) tokenizedInputExtensionPool.pop(); result.setInput(input); return result; } } return new TokenizedInputDictionaryExtension(this, input); }
static String getBody(SamTokenizer f) throws TokenizerException { try { String asmCode = ""; Boolean returnFlag = false; Boolean tempFlag; myCheck(f, '{'); switch (f.peekAtKind()) { case WORD: // Check if it is a variable declaration. while (f.check("int")) { asmCode += getVariables(f); myCheck(f, ';'); } // Parse all the statement before }. while (!f.check('}')) { asmCode += getStmt(f); tempFlag = returnFlags.pop(); if (tempFlag) { returnFlag = true; } } if (!returnFlag) throw new TokenizerException("Error: No return."); return asmCode; case OPERATOR: while (!f.check('}')) { asmCode += getStmt(f); tempFlag = returnFlags.pop(); if (tempFlag) { returnFlag = true; } } if (!returnFlag) throw new TokenizerException("Error: No return."); return asmCode; default: throw new TokenizerException("Error: Invalid body."); } } catch (Exception e) { System.out.println(e.getMessage()); throw new TokenizerException("Error: Invalid body."); } }
/** * Calculates the length of the the sub-path in a _transition path, that is used only by a given * string. * * @param str a String corresponding to a _transition path from sourceNode * @return an int denoting the size of the sub-path in the _transition path corresponding to * {@code str} that is only used by {@code str} */ private int calculateSoleTransitionPathLength(String str) { Stack<MDAGNode> transitionPathNodeStack = sourceNode.getTransitionPathNodes(str); transitionPathNodeStack.pop(); // The MDAGNode at the top of the stack is not needed // (we are processing the outgoing transitions of nodes inside str's _transition path, // the outgoing transitions of the MDAGNode at the top of the stack are outside this path) transitionPathNodeStack.trimToSize(); // Process each node in transitionPathNodeStack, using each to determine whether the // _transition path corresponding to str is only used by str. This is true if and only if // each node in the _transition path has a single outgoing _transition and is not an accept // state. while (!transitionPathNodeStack.isEmpty()) { MDAGNode currentNode = transitionPathNodeStack.peek(); if (currentNode.getOutgoingTransitions().size() <= 1 && !currentNode.isAcceptNode()) transitionPathNodeStack.pop(); else break; } ///// return (transitionPathNodeStack.capacity() - transitionPathNodeStack.size()); }
private static void netxsurgery() throws Exception { /* Force off NetX codebase classloading. */ Class<?> nxc; try { nxc = Class.forName("net.sourceforge.jnlp.runtime.JNLPClassLoader"); } catch (ClassNotFoundException e1) { try { nxc = Class.forName("netx.jnlp.runtime.JNLPClassLoader"); } catch (ClassNotFoundException e2) { throw (new Exception("No known NetX on classpath")); } } ClassLoader cl = MainFrame.class.getClassLoader(); if (!nxc.isInstance(cl)) { throw (new Exception("Not running from a NetX classloader")); } Field cblf, lf; try { cblf = nxc.getDeclaredField("codeBaseLoader"); lf = nxc.getDeclaredField("loaders"); } catch (NoSuchFieldException e) { throw (new Exception("JNLPClassLoader does not conform to its known structure")); } cblf.setAccessible(true); lf.setAccessible(true); Set<Object> loaders = new HashSet<Object>(); Stack<Object> open = new Stack<Object>(); open.push(cl); while (!open.empty()) { Object cur = open.pop(); if (loaders.contains(cur)) continue; loaders.add(cur); Object curl; try { curl = lf.get(cur); } catch (IllegalAccessException e) { throw (new Exception("Reflection accessibility not available even though set")); } for (int i = 0; i < Array.getLength(curl); i++) { Object other = Array.get(curl, i); if (nxc.isInstance(other)) open.push(other); } } for (Object cur : loaders) { try { cblf.set(cur, null); } catch (IllegalAccessException e) { throw (new Exception("Reflection accessibility not available even though set")); } } }
/** * Test load all sg ffiles. * * @throws IOException Signals that an I/O exception has occurred. */ public void testLoadAllSGFfiles() throws IOException { Stack<String> files = new Stack<String>(); files.push("sgf/2004-12"); int count = 0; while (files.size() > 0 && count <= 10) { String filename = files.pop(); File file = new File(filename); count++; if (DEBUG) System.err.println("examining \"" + filename + "\""); if (file.exists()) { if (!file.isDirectory()) { // System.err.println("\"" + filename + "\" is not a // directory, parsing as an SGF file"); Game game = Game.loadFromFile(file); if (game.getSize() == 19) { Iterator<Move> i = game.getMoves(); Move move = null; BoardI board = new SmallerBoard(game.getSize()); // System.err.println("board size is: \"" + // goGame.getSize() // + "\""); while (i.hasNext()) { move = i.next(); assertNotNull(move); // System.err.print("move: \"" + move + "\""); // assertTrue("" + board + "\n" + // move.toString(),board.isLegalMove(move)); board = board.newBoard(move); // System.err.println(" board size is: \"" + // board.getSize() + "\""); } // System.err.println(); } } else { if (DEBUG) System.err.println("\"" + filename + "\" is a directory"); if (!file.getName().contains(".svn")) { String[] children = file.list(); for (int i = 0; i < children.length; i++) { // System.err.println("pushing \"" + children[i] + // "\""); files.push(filename + "/" + children[i]); } } } } } }
void topologicalSort() { Stack s = new Stack(); boolean traverse[] = new boolean[n]; for (int i = 0; i < n; i++) traverse[i] = false; for (int i = 0; i < n; i++) { if (!traverse[i]) topSort(i, traverse, s); } while (!s.isEmpty()) { System.out.print(((int) s.peek() + 1) + " "); s.pop(); } System.out.println(); }
int store(BytecodeBuffer b, int start, int end) { ByteArray a = wrappers.isEmpty() ? null : (ByteArray) wrappers.pop(); if (a == null) { a = newByteArray(); } a.clear(); a.b = b; a.start = start; a.end = end; a.init(); Integer index = IntegerPool.getNumber(map.size() + 1); map.put(a, index); return index.intValue(); }
static String getBlock(SamTokenizer f) throws TokenizerException { try { String asmCode = ""; Boolean returnFlag = false; Boolean tempFlag; while (!f.check('}')) { asmCode += getStmt(f); tempFlag = returnFlags.pop(); if (tempFlag) { returnFlag = true; } } if (!returnFlag) returnFlags.push(false); else returnFlags.push(true); return asmCode; } catch (Exception e) { System.out.println(e.getMessage()); throw new TokenizerException("Error: Invalid block."); } }
/** * Method to retrieve all test defining XML files in given directory. Hierarchy of folders is * supported. * * @param startDir the directory to hold the files * @return list of test files as filename paths */ public static List<File> getTestFiles(final String startDir) { /* file names to be returned */ final List<File> files = new ArrayList<File>(); /* Stack to hold potential sub directories */ final Stack<File> dirs = new Stack<File>(); /* start directory */ final File startdir = new File(startDir); if (startdir.isDirectory()) { dirs.push(startdir); } /* walk through the directories */ while (dirs.size() > 0) { File file = dirs.pop(); File[] found = file.listFiles( new FilenameFilter() { public boolean accept(File dir, String name) { File tmp = new File(dir.getPath() + "/" + name); /* Only allowing XML files as spring configuration files */ return (name.endsWith(".xml") || tmp.isDirectory()) && !name.startsWith("CVS") && !name.startsWith(".svn"); } }); for (int i = 0; i < found.length; i++) { /* Subfolder support */ if (found[i].isDirectory()) { dirs.push(found[i]); } else { files.add(found[i]); } } } return files; }
public LinkedList<DirEdge> getFlowPath() { // do a depth first search to see if there is path from source to the sink boolean[] visited = new boolean[v]; Arrays.fill(visited, false); Stack<Integer> tobeVisited = new Stack<Integer>(); tobeVisited.push(source); int[] predecessor = new int[v]; Arrays.fill(predecessor, -1); while (!tobeVisited.isEmpty()) { int vertex = tobeVisited.pop(); if (!visited[vertex]) { // System.out.println("Visiting " + vertex); visited[vertex] = true; // put vertex's next hop nodes into the stack ListIterator it = edges.get(vertex).listIterator(); while (it.hasNext()) { DirEdge e = (DirEdge) it.next(); if (predecessor[e.end] == -1) { predecessor[e.end] = vertex; } if (e.end == sink) { return constructPath(predecessor); } if (!visited[e.end]) { tobeVisited.push(e.end); } } } } return null; // we cannot find an augment path }