private T evaluate(int level) { Deque<T> q = elements[level]; BinaryOperator<T> op = operations[level]; T result = q.pollFirst(); while (!q.isEmpty()) { result = op.apply(result, q.pollFirst()); } return result; }
private static void add(float x, float y) { Deque<Vector2f> tmp = new ArrayDeque<Vector2f>(); while (!graphRes.isEmpty() && graphRes.getFirst().x < x) { tmp.addLast(graphRes.pollFirst()); } tmp.addLast(new Vector2f(x, y)); while (!graphRes.isEmpty()) { tmp.addLast(graphRes.pollFirst()); } graphRes = tmp; while (y / graph1dY > height) { frame.jSliderdY1.setValue(frame.jSliderdY1.getValue() + 1); } }
private void flatten() { // We use iterative traversal as recursion may exceed the stack size limit. final char[] chars = new char[length]; int pos = length; // Strings are most often composed by appending to the end, which causes ConsStrings // to be very unbalanced, with mostly single string elements on the right and a long // linear list on the left. Traversing from right to left helps to keep the stack small // in this scenario. final Deque<CharSequence> stack = new ArrayDeque<>(); stack.addFirst(left); CharSequence cs = right; do { if (cs instanceof ConsString) { final ConsString cons = (ConsString) cs; stack.addFirst(cons.left); cs = cons.right; } else { final String str = (String) cs; pos -= str.length(); str.getChars(0, str.length(), chars, pos); cs = stack.isEmpty() ? null : stack.pollFirst(); } } while (cs != null); left = new String(chars); right = ""; flat = true; }
/** * Flushes the events. * * <p>NOTE: not threadsafe! Has to be called in the opengl thread if in opengl mode! */ public void flushEvents() { /* //FIXME DEBUG TEST REMOVE! int count = 0; for (Iterator<MTInputEvent> iterator = eventQueue.iterator(); iterator.hasNext();){ MTInputEvent e = (MTInputEvent) iterator.next(); if (e instanceof MTFingerInputEvt) { MTFingerInputEvt fe = (MTFingerInputEvt) e; if (fe.getId() == MTFingerInputEvt.INPUT_ENDED) { count++; } } } if (count >= 2){ System.out.println("--2 INPUT ENDED QUEUED!--"); } int iCount = 0; for (IinputSourceListener listener : inputListeners){ if (listener.isDisabled()){ iCount++; } } if (iCount >= inputListeners.size() && !eventQueue.isEmpty()){ System.out.println("--ALL INPUT PROCESSORS DISABLED!--"); } */ if (!eventQueue.isEmpty()) { // System.out.print("START FLUSH CURSOR: " + // ((MTFingerInputEvt)eventQueue.peek()).getCursor().getId() + " Evt-ID: " + // ((MTFingerInputEvt)eventQueue.peek()).getId()+ " "); // To ensure that all global input processors of the current scene // get the queued events even if through the result of one event processing the scene // gets changed and the currents scenes processors get disabled // Also ensure that all queued events get flushed to the scene although // as a result this scenes input processors get disabled // TODO do this only at real scene change? // -> else if we disable input processors it may get delayed.. // FIXME problem that this can get called twice - because called again in initiateScenechange inputProcessorsToFireTo.clear(); for (IinputSourceListener listener : inputListeners) { if (!listener.isDisabled()) { inputProcessorsToFireTo.add(listener); } } while (!eventQueue.isEmpty()) { try { MTInputEvent te = eventQueue.pollFirst(); this.fireInputEvent(te); } catch (NoSuchElementException e) { e.printStackTrace(); // System.err.println(e.getMessage()); } } // System.out.println("END FLUSH"); } }
/** * Get a new {@link RingoWorker}. * * @return a worker instance. */ public RingoWorker getWorker() { RingoWorker worker = workers.pollFirst(); if (worker == null) { worker = new RingoWorker(this); } return worker; }
public int BFS(int end) { Deque<Vertice> q = new ArrayDeque(); Set closed = new HashSet(); Vertice initialVertice = cache.get(1); q.addLast(initialVertice); closed.add(initialVertice); while (!q.isEmpty()) { Vertice tmp = q.pollFirst(); if (inverseCache.get(tmp) == end) return inverseCache.get(tmp); for (int x = 0; x < tmp.neighbours.size(); x++) { Vertice o = tmp.neighbours.get(x); if (!closed.contains(o)) { closed.add(o); q.addLast(o); } } } return 0; }
public static void nextW_DeltaSearch() { if (!userRequestedW.isEmpty()) { w = userRequestedW.pollFirst(); return; } if (!wasFract[0]) { w = leftW; wasFract[0] = true; return; } else if (!wasFract[wasFract.length - 1]) { w = rightW; wasFract[wasFract.length - 1] = true; return; } else { for (int i = maxFractPow2; i > 0; i--) { for (int j = 0; (1 << (i - 1)) + j * (1 << i) < wasFract.length; j++) { float tmp = leftW + (rightW - leftW) * (1 + 2 * j) / (float) (1 << (maxFractPow2 + 1 - i)); if (!wasFract[(1 << (i - 1)) + j * (1 << i)] && tmp >= chosenLeftW && tmp <= chosenRightW) { w = tmp; wasFract[(1 << (i - 1)) + j * (1 << i)] = true; return; } } } } frame.stop(); JOptionPane.showMessageDialog(frame, "Максимальная точность на данном отрезке достигнута"); }
private String getPureTextFromFile() { StringBuilder entry = new StringBuilder(); while (!pureTextFromFile.isEmpty()) { entry.append(pureTextFromFile.pollFirst()); } return entry.toString(); }
public OMPTask getTask() { taskLock.lock(); try { return tasks.pollFirst(); } finally { taskLock.unlock(); } }
static TShortIntHashMap popFacets() { Deque<TShortIntHashMap> deque = cache.get().get(); if (deque.isEmpty()) { deque.add(new TShortIntHashMap()); } TShortIntHashMap facets = deque.pollFirst(); facets.clear(); return facets; }
/** * This method will be called by Dispatcher, and will be repeated till return false. * * @param data * @return True if data was written to buffer, False indicating that there are not any more data * to write. */ @Override protected final boolean writeData(ByteBuffer data) { synchronized (guard) { LsServerPacket packet = sendMsgQueue.pollFirst(); if (packet == null) return false; packet.write(this, data); return true; } }
@Override public PyString next() { if (closed) { throw Py.StopIteration(""); } PyString chunk = chunks.pollFirst(); if (chunk == null) { return Py.EmptyString; } else { return chunk; } }
protected ArrayList<Trace<T>> buildTraces(T startBlock) { ArrayList<Trace<T>> traces = new ArrayList<>(); // add start block worklist.add(startBlock); // process worklist while (!worklist.isEmpty()) { T block = worklist.pollFirst(); assert block != null; if (!processed(block)) { traces.add(new Trace<>(startTrace(block, traces.size()))); } } return traces; }
public int inc(int bom, int dis) { bom %= size; if (bom == 0) { bom = size; } Deque<Integer> tempStack = new LinkedList<Integer>(); for (int i = 0; i < bom; i++) { tempStack.offerLast(stack.pollFirst() + dis); } for (int i = 0; i < bom; i++) { stack.offerFirst(tempStack.pollLast()); } return stack.peekLast(); }
private boolean explore(char[][] board, Pair newCell, Deque<Pair> emptyGrids) { for (int i = 1; i < 10; i++) { board[newCell.row][newCell.col] = (char) ('0' + i); if (isValidSudoku(board, newCell.row, newCell.col)) { if (emptyGrids.isEmpty() || explore(board, emptyGrids.pollFirst(), emptyGrids)) { return true; } } board[newCell.row][newCell.col] = '.'; } emptyGrids.addFirst(newCell); return false; }
public TreeNode sinkZerosInBT2(TreeNode root) { if (deque == null) deque = new LinkedList<TreeNode>(); if (root == null) return null; if (root.val == 0) deque.addLast(root); else { if (!deque.isEmpty()) { swap(root, deque.pollFirst()); deque.addLast(root); // need to push this new zero-node to end of deque } } sinkZerosInBT2(root.left); sinkZerosInBT2(root.right); if (deque.peekLast() == root) // there's no non-zero node for us to swap, poll the zero node deque.pollLast(); return root; }
private void bfs(int node, boolean[] marked) { Deque<Integer> deque = new ArrayDeque<Integer>(); marked[node] = true; sorted.add(node); deque.addLast(node); while (deque.size() > 0) { int vertax = deque.pollFirst(); List<Integer> list = this.graph.adj(vertax); for (Integer ele : list) { if (!marked[ele]) { marked[ele] = true; sorted.add(ele); deque.addLast(ele); } } } }
public List<Integer> maxWindows(int[] array, int k) { List<Integer> result = new ArrayList<Integer>(); Deque<Integer> deque = new LinkedList<>(); for (int i = 0; i < array.length; i++) { while (!deque.isEmpty() && array[deque.peekLast()] <= array[i]) { deque.pollLast(); } deque.offerLast(i); if (i - k == deque.peekFirst()) { deque.pollFirst(); } if (i >= k - 1) { result.add(array[deque.peekFirst()]); } } return result; }
public static void reorderList(ListNode head) { if (head == null || head.next == null) return; Deque deque = new LinkedList<ListNode>(); ListNode current = head; while (current != null) { deque.addLast(current); current = current.next; } ListNode result = new ListNode(0); while (!deque.isEmpty()) { result.next = (ListNode) deque.pollFirst(); result = result.next; if (!deque.isEmpty()) { result.next = (ListNode) deque.pollLast(); result = result.next; } } result.next = null; }
/* * (non-Javadoc) * * @see * gtna.transformation.sampling.AWalker#selectNextNode(java.util.Collection) */ @Override protected Node selectNextNode(Collection<Node> candidates) { Node n = null; List<Node> c = new ArrayList<Node>(); Collection<Node> cc = new ArrayList<Node>(); while (n == null) { if (nextQ.size() > 0) { c.add(nextQ.pollFirst()); cc = this.filterCandidates(c); if (cc.size() > 0) { n = cc.toArray(new Node[0])[0]; } } else { cc = super.getRestartNodes(); n = cc.toArray(new Node[0])[0]; } } return n; }
public int[] larger(int input[]) { Deque<Integer> stack = new LinkedList<Integer>(); int result[] = new int[input.length]; for (int i = 0; i < result.length; i++) { result[i] = -1; } stack.offerFirst(0); for (int i = 1; i < input.length; i++) { while (stack.size() > 0) { int t = stack.peekFirst(); if (input[t] < input[i]) { result[t] = i; stack.pollFirst(); } else { break; } } stack.offerFirst(i); } return result; }
public static void nextW_TernarySearch() { if (!userRequestedW.isEmpty()) { w = userRequestedW.pollFirst(); return; } if (Float.isNaN(A1_tern)) { w = leftW_tern + (rightW_tern - leftW_tern) / 3f; } else if (Float.isNaN(A2_tern)) { w = leftW_tern + 2f * (rightW_tern - leftW_tern) / 3f; } else { if (A1_tern < A2_tern) { leftW_tern = leftW_tern + (rightW_tern - leftW_tern) / 3f; } else if (A1_tern > A2_tern) { rightW_tern = leftW_tern + 2 * (rightW_tern - leftW_tern) / 3f; } else { leftW_tern = leftW_tern + (rightW_tern - leftW_tern) / 3f; rightW_tern = leftW_tern + 2 * (rightW_tern - leftW_tern) / 3f; } A1_tern = Float.NaN; A2_tern = Float.NaN; nextW_TernarySearch(); } }
public String removeDuplicateLetters(String s) { Deque<Character> stack = new LinkedList<>(); Map<Character, Integer> count = new HashMap<>(); for (int i = 0; i < s.length(); i++) { count.compute( s.charAt(i), (key, val) -> { if (val == null) { return 1; } else { return val + 1; } }); } Set<Character> visited = new HashSet<>(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); count.put(ch, count.get(ch) - 1); if (visited.contains(ch)) { continue; } while (!stack.isEmpty() && stack.peekFirst() > ch && count.get(stack.peekFirst()) > 0) { visited.remove(stack.peekFirst()); stack.pollFirst(); } stack.offerFirst(ch); visited.add(ch); } StringBuffer buff = new StringBuffer(); while (!stack.isEmpty()) { buff.append(stack.pollLast()); } return buff.toString(); }
public static void main(String[] args) { String s1 = "ABCDEBF"; System.out.println(s1.length()); System.out.println(s1.charAt(4)); System.out.println(s1.indexOf("B")); System.out.println(s1.substring(0, 2)); System.out.println(s1.lastIndexOf("B")); System.out.println(s1.toUpperCase()); System.out.println(s1.toLowerCase()); System.out.println(s1.contains("B")); System.out.println(s1.concat("GP")); System.out.println(s1.startsWith("A")); System.out.println(s1.endsWith("P")); System.out.println(s1.isEmpty()); char[] s2 = s1.toCharArray(); Deque<Character> qc = new LinkedList<>(); for (int i = 0; i < s2.length; i++) { qc.offerFirst(s2[i]); } while (!qc.isEmpty()) { System.out.println(qc.pollFirst()); } }
public void solveSudoku(char[][] board) { Deque<Pair> availableCells = findAllEmptyGrid(board); explore(board, availableCells.pollFirst(), availableCells); }
private List<BooleanFormula> computeBlockFormulas(final ARGState pRoot) throws CPATransferException, InterruptedException { final Map<ARGState, ARGState> callStacks = new HashMap<>(); // contains states and their next higher callstate final Map<ARGState, PathFormula> finishedFormulas = new HashMap<>(); final List<BooleanFormula> abstractionFormulas = new ArrayList<>(); final Deque<ARGState> waitlist = new ArrayDeque<>(); // initialize assert pRoot.getParents().isEmpty() : "rootState must be the first state of the program"; callStacks.put(pRoot, null); // main-start has no callstack finishedFormulas.put(pRoot, pfmgr.makeEmptyPathFormula()); waitlist.addAll(pRoot.getChildren()); // iterate over all elements in the ARG with BFS while (!waitlist.isEmpty()) { final ARGState currentState = waitlist.pollFirst(); if (finishedFormulas.containsKey(currentState)) { continue; // already handled } if (!finishedFormulas.keySet().containsAll(currentState.getParents())) { // parent not handled yet, re-queue current element and wait for all parents waitlist.addLast(currentState); continue; } // collect formulas for current location final List<PathFormula> currentFormulas = new ArrayList<>(currentState.getParents().size()); final List<ARGState> currentStacks = new ArrayList<>(currentState.getParents().size()); for (ARGState parentElement : currentState.getParents()) { PathFormula parentFormula = finishedFormulas.get(parentElement); final CFAEdge edge = parentElement.getEdgeToChild(currentState); assert edge != null : "ARG is invalid: parent has no edge to child"; final ARGState prevCallState; // we enter a function, so lets add the previous state to the stack if (edge.getEdgeType() == CFAEdgeType.FunctionCallEdge) { prevCallState = parentElement; } else if (edge.getEdgeType() == CFAEdgeType.FunctionReturnEdge) { // we leave a function, so rebuild return-state before assigning the return-value. // rebuild states with info from previous state assert callStacks.containsKey(parentElement); final ARGState callState = callStacks.get(parentElement); assert extractLocation(callState).getLeavingSummaryEdge().getSuccessor() == extractLocation(currentState) : "callstack does not match entry of current function-exit."; assert callState != null || currentState.getChildren().isEmpty() : "returning from empty callstack is only possible at program-exit"; prevCallState = callStacks.get(callState); parentFormula = rebuildStateAfterFunctionCall( parentFormula, finishedFormulas.get(callState), (FunctionExitNode) extractLocation(parentElement)); } else { assert callStacks.containsKey(parentElement); // check for null is not enough prevCallState = callStacks.get(parentElement); } final PathFormula currentFormula = pfmgr.makeAnd(parentFormula, edge); currentFormulas.add(currentFormula); currentStacks.add(prevCallState); } assert currentFormulas.size() >= 1 : "each state except root must have parents"; assert currentStacks.size() == currentFormulas.size() : "number of callstacks must match predecessors"; // merging after functioncall with different callstates is ugly. // this is also guaranteed by the abstraction-locations at function-entries // (--> no merge of states with different latest abstractions). assert Sets.newHashSet(currentStacks).size() <= 1 : "function with multiple entry-states not supported"; callStacks.put(currentState, currentStacks.get(0)); PathFormula currentFormula; final PredicateAbstractState predicateElement = extractStateByType(currentState, PredicateAbstractState.class); if (predicateElement.isAbstractionState()) { // abstraction element is the start of a new part of the ARG assert waitlist.isEmpty() : "todo should be empty, because of the special ARG structure"; assert currentState.getParents().size() == 1 : "there should be only one parent, because of the special ARG structure"; // finishedFormulas.clear(); // free some memory // TODO disabled, we need to keep callStates for later usage // start new block with empty formula currentFormula = getOnlyElement(currentFormulas); abstractionFormulas.add(currentFormula.getFormula()); currentFormula = pfmgr.makeEmptyPathFormula(currentFormula); } else { // merge the formulas Iterator<PathFormula> it = currentFormulas.iterator(); currentFormula = it.next(); while (it.hasNext()) { currentFormula = pfmgr.makeOr(currentFormula, it.next()); } } assert !finishedFormulas.containsKey(currentState) : "a state should only be finished once"; finishedFormulas.put(currentState, currentFormula); waitlist.addAll(currentState.getChildren()); } return abstractionFormulas; }