public void reverseNotes() { final ArrayDeque<String> headReversed = new ArrayDeque<>(); final ArrayDeque<AbcEvent> notesReversed = new ArrayDeque<>(); int lineIdx = 0; boolean head = true; while (lineIdx < lines.size()) { final String line = lines.get(lineIdx++); if (notesRaw.get(0) == line) { break; } else if (head) { // keep only documentary lines at the start headReversed.addLast(line); } } final String title = this.title.toString(); this.title.setLength(0); this.title.append(title); lines.clear(); if (notes.isEmpty()) parse(); notesRaw.clear(); lines.addAll(headReversed); final Map<Class<? extends AbcEvent>, AbcEvent> lastEventMap = new HashMap<>(); lastEventMap.put(AbcVolumeChange.class, new AbcVolumeChange("mf")); final Map<String, List<AbcNote>> continuations = new HashMap<>(); for (final AbcEvent e : notes) { if (e.isMeta()) { final AbcEvent lastEvent = lastEventMap.get(e.getClass()); if (lastEvent != null) { notesReversed.addFirst(lastEvent); } lastEventMap.put(e.getClass(), e); } else { // a- <--last // a/ <-- e // reversed: // a/- <-- e // a <-- last ContiunableAbcEvent ce = (ContiunableAbcEvent) e; ce.reverseContinuation(continuations); notesReversed.addFirst(e); } } if (!continuations.isEmpty()) { // TODO possible and needs extra care? } notesReversed.addFirst(lastEventMap.get(AbcVolumeChange.class)); notes.clear(); notes.addAll(notesReversed); }
/** Build a new trace starting at {@code block}. */ @SuppressWarnings("try") private Collection<T> startTrace(T block, int traceNumber) { ArrayDeque<T> trace = new ArrayDeque<>(); try (Indent i = Debug.logAndIndent("StartTrace: " + block)) { try (Indent indentFront = Debug.logAndIndent("Head:")) { for (T currentBlock = block; currentBlock != null; currentBlock = selectPredecessor(currentBlock)) { addBlockToTrace(currentBlock, traceNumber); trace.addFirst(currentBlock); } } /* Number head blocks. Can not do this in the loop as we go backwards. */ int blockNr = 0; for (T b : trace) { b.setLinearScanNumber(blockNr++); } try (Indent indentBack = Debug.logAndIndent("Tail:")) { for (T currentBlock = selectSuccessor(block); currentBlock != null; currentBlock = selectSuccessor(currentBlock)) { addBlockToTrace(currentBlock, traceNumber); trace.addLast(currentBlock); /* This time we can number the blocks immediately as we go forwards. */ currentBlock.setLinearScanNumber(blockNr++); } } } Debug.log("Trace: %s", trace); return trace; }
private void createPath() { this.isFinished = true; this.isPathFound = true; this.isRunning = false; Node curr = this.goal; // create path ArrayDeque<Node> foundPath = new ArrayDeque<>(); foundPath.addFirst(curr); while (parentMap.containsKey(curr)) { curr = parentMap.get(curr); foundPath.addFirst(curr); } path = new Path(foundPath.toArray(new Node[0])); }
private void processReferences( JsonSchemaObject root, Set<JsonSchemaObject> objects, @Nullable JsonSchemaExportedDefinitions definitions) { final ArrayDeque<JsonSchemaObject> queue = new ArrayDeque<>(); queue.addAll(objects); int control = 10000; while (!queue.isEmpty()) { if (--control == 0) throw new RuntimeException("cyclic definitions search"); final JsonSchemaObject current = queue.removeFirst(); if ("#".equals(current.getRef())) continue; if (current.getRef() != null) { final JsonSchemaObject definition = findDefinition(myKey, current.getRef(), root, definitions); if (definition == null) { if (definitions == null) { // just skip current item current.setRef(null); continue; } throw new RuntimeException("Can not find definition: " + current.getRef()); } if (definition.getRef() != null && !"#".equals(definition.getRef())) { queue.addFirst(current); queue.addFirst(definition); continue; } final JsonSchemaObject copy = new JsonSchemaObject(); copy.setDefinitionAddress(current.getRef()); copy.mergeValues(definition); copy.mergeValues(current); current.copyValues(copy); current.setRef(null); } } }
synchronized void removeUpTo(long l) { long bytesFreed = 0; while (!chunks.isEmpty()) { Chunk c = chunks.getFirst(); if (c.getSeqID() > l) chunks.addFirst(c); else bytesFreed += c.getData().length; } if (bytesFreed > 0) { dataSizeBytes -= bytesFreed; notifyAll(); } }
/** * Thread synchronized method to prevent concurrent modification of buffer * * @param op * @param add * @return Frame being modified */ private synchronized Frame bufferOp(BufferOp op, Frame add) { switch (op) { case ADD: buffer.addFirst(add); return add; case ADDLAST: buffer.addLast(add); return add; case REM: return buffer.pop(); default: break; } return null; }
protected void meshClean(DelaunayTriangle triangle) { DelaunayTriangle t1, t2; if (triangle != null) { ArrayDeque<DelaunayTriangle> deque = new ArrayDeque<DelaunayTriangle>(); deque.addFirst(triangle); triangle.isInterior(true); while (!deque.isEmpty()) { t1 = deque.removeFirst(); _triUnit.addTriangle(t1); for (int i = 0; i < 3; ++i) { if (!t1.cEdge[i]) { t2 = t1.neighbors[i]; if (t2 != null && !t2.isInterior()) { t2.isInterior(true); deque.addLast(t2); } } } } } }
@Override public void step() { if (this.isFinished()) { return; } if (openedList.isEmpty()) { this.isFinished = true; this.isRunning = false; return; } Node curr = openedList.pop(); for (Map.Entry<Direction, Link> item : curr.links.entrySet()) { Direction dir = item.getKey(); Link link = item.getValue(); Node next = link.n1 == curr ? link.n2 : link.n1; if (next == goal) { parentMap.put(next, curr); createPath(); return; } if (closedList.contains(next)) { // do nothing or reopen? } else if (openedList.contains(next)) { // do nothing? } else { openedList.addFirst(next); parentMap.put(next, curr); } } closedList.add(curr); steps++; }
protected void loadLogFile() { fileChooser.setMultiSelectionEnabled(true); if (JFileChooser.APPROVE_OPTION != fileChooser.showOpenDialog(this)) return; File[] files = fileChooser.getSelectedFiles(); for (File file : files) { BufferedReader br = null; ArrayDeque<String[]> buffer = new ArrayDeque<String[]>(); try { br = new BufferedReader(new FileReader(file.getAbsoluteFile())); String line = br.readLine(); if (line != null) { String[] elements = line.split("(\\s*)?,(\\s*)?", -1); getColumnsFilters(elements); boolean resetColumns = false; if (logThrottleAngleColIdx >= 0 || logFfbColIdx >= 0 || logSdColIdx >= 0 || (logWbAfrColIdx >= 0 && isOl) || (logStockAfrColIdx >= 0 && !isOl) || (logAfLearningColIdx >= 0 && !isOl) || (logAfCorrectionColIdx >= 0 && !isOl) || logRpmColIdx >= 0 || logMafColIdx >= 0 || logIatColIdx >= 0 || logMpColIdx >= 0) { if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog( null, "Would you like to reset column names or filter values?", "Columns/Filters Reset", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE)) resetColumns = true; } if (resetColumns || logThrottleAngleColIdx < 0 || logFfbColIdx < 0 || logSdColIdx < 0 || (logWbAfrColIdx < 0 && isOl) || (logStockAfrColIdx < 0 && !isOl) || (logAfLearningColIdx < 0 && !isOl) || (logAfCorrectionColIdx < 0 && !isOl) || logRpmColIdx < 0 || logMafColIdx < 0 || logIatColIdx < 0 || logMpColIdx < 0) { ColumnsFiltersSelection selectionWindow = new VEColumnsFiltersSelection(false); if (!selectionWindow.getUserSettings(elements) || !getColumnsFilters(elements)) return; } if (logClOlStatusColIdx == -1) clValue = -1; String[] flds; String[] afrflds; boolean removed = false; int i = 2; int clol = -1; int row = getLogTableEmptyRow(); double thrtlMaxChange2 = thrtlMaxChange + thrtlMaxChange / 2.0; double throttle = 0; double pThrottle = 0; double ppThrottle = 0; double afr = 0; double rpm; double ffb; double iat; clearRunTables(); setCursor(new Cursor(Cursor.WAIT_CURSOR)); for (int k = 0; k <= afrRowOffset && line != null; ++k) { line = br.readLine(); if (line != null) buffer.addFirst(line.split(",", -1)); } try { while (line != null && buffer.size() > afrRowOffset) { afrflds = buffer.getFirst(); flds = buffer.removeLast(); line = br.readLine(); if (line != null) buffer.addFirst(line.split(",", -1)); ppThrottle = pThrottle; pThrottle = throttle; throttle = Double.valueOf(flds[logThrottleAngleColIdx]); try { if (row > 0 && Math.abs(pThrottle - throttle) > thrtlMaxChange) { if (!removed) Utils.removeRow(row--, logDataTable); removed = true; } else if (row <= 0 || Math.abs(ppThrottle - throttle) <= thrtlMaxChange2) { // Filters afr = (isOl ? Double.valueOf(afrflds[logWbAfrColIdx]) : Double.valueOf(afrflds[logStockAfrColIdx])); rpm = Double.valueOf(flds[logRpmColIdx]); ffb = Double.valueOf(flds[logFfbColIdx]); iat = Double.valueOf(flds[logIatColIdx]); if (clValue != -1) clol = Integer.valueOf(flds[logClOlStatusColIdx]); boolean flag = isOl ? ((afr <= afrMax || throttle >= thrtlMin) && afr <= afrMax) : (afrMin <= afr); if (flag && clol == clValue && rpmMin <= rpm && ffbMin <= ffb && ffb <= ffbMax && iat <= iatMax) { removed = false; if (!isOl) trims.add( Double.valueOf(flds[logAfLearningColIdx]) + Double.valueOf(flds[logAfCorrectionColIdx])); Utils.ensureRowCount(row + 1, logDataTable); logDataTable.setValueAt(rpm, row, 0); logDataTable.setValueAt(iat, row, 1); logDataTable.setValueAt(Double.valueOf(flds[logMpColIdx]), row, 2); logDataTable.setValueAt(ffb, row, 3); logDataTable.setValueAt(afr, row, 4); logDataTable.setValueAt(Double.valueOf(flds[logMafColIdx]), row, 5); logDataTable.setValueAt(Double.valueOf(flds[logSdColIdx]), row, 6); row += 1; } else removed = true; } else removed = true; } catch (NumberFormatException e) { logger.error(e); JOptionPane.showMessageDialog( null, "Error parsing number at " + file.getName() + " line " + i + ": " + e, "Error processing file", JOptionPane.ERROR_MESSAGE); return; } i += 1; } } finally { setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } } } catch (Exception e) { logger.error(e); JOptionPane.showMessageDialog(null, e, "Error opening file", JOptionPane.ERROR_MESSAGE); } finally { if (br != null) { try { br.close(); } catch (IOException e) { logger.error(e); } } } } }
/* * A function that generates a list of the series of moves to play that are * considered the best by our heuristic function. * * @param board the board to be used to manipulate * * @param z the depth for the algorithm to go to. * * @return an ArrayDeque containing the series of recommended moves */ public static ArrayDeque<String> AStar(int[][] board, int z) { Comparator<Node> comparator = new BestMoveComparator(); PriorityQueue<Node> openList = new PriorityQueue<Node>(z, comparator); PriorityQueue<Node> closedList = new PriorityQueue<Node>(z, comparator); ArrayDeque<String> initialMoves = new ArrayDeque<String>(); Node initial = new Node( Moves.countScore(GUI.Threes.board), Moves.Hscore(GUI.Threes.board)[1], initialMoves); openList.add(initial); // add initial board to openList ArrayDeque<String> moves = new ArrayDeque<String>(); moves.clear(); int HScore = 0; int Score = 0; int i = 0; while (!openList.isEmpty() && i < z) { Node node = openList.remove(); closedList.add(node); LinkedList<Object> temp = new LinkedList<Object>(); node.moves.add("D"); temp = Moves.doMove(board, node.moves, false); if ((int) temp.peek() != -1) { Node down = new Node((Integer) temp.get(0), (Integer) temp.get(1), node.moves.clone()); openList.offer(down); } node.moves.removeLast(); node.moves.add("U"); temp = Moves.doMove(board, node.moves, false); if ((int) temp.peek() != -1) { Node up = new Node((Integer) temp.get(0), (Integer) temp.get(1), node.moves.clone()); openList.offer(up); } node.moves.removeLast(); node.moves.add("L"); temp = Moves.doMove(board, node.moves, false); if ((int) temp.peek() != -1) { int tempint = (Integer) temp.get(0); Node left = new Node(tempint, (Integer) temp.get(1), node.moves.clone()); openList.offer(left); } node.moves.removeLast(); node.moves.add("R"); temp = Moves.doMove(board, node.moves, false); if ((int) temp.peek() != -1) { Node right = new Node((Integer) temp.get(0), (Integer) temp.get(1), node.moves.clone()); openList.offer(right); } node.moves.removeLast(); i++; } if (openList.size() > 1) { Node bestOpen = openList.remove(); closedList.add(bestOpen); } Node node = closedList.remove(); Score = node.score; HScore = node.hScore; moves = node.moves; String heurScore = "Heuristic Score is: " + HScore; String scorescore = "Game Score is: " + Score; moves.addFirst(heurScore); moves.addFirst(scorescore); return moves; }
public static void recur(int[][] board, int z) { int[][] tempBoard = new int[4][4]; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { tempBoard[i][j] = board[i][j]; } } Moves.storeNext(); // GUI.ThreesGUI gui = new GUI.ThreesGUI(); ArrayDeque<String> finalmoves = new ArrayDeque<String>(); ArrayDeque<String> temp = new ArrayDeque<String>(); LinkedList<Object> temp2 = new LinkedList<Object>(); LinkedList<Object> temp3 = new LinkedList<Object>(); String nextMove = ""; for (int i = 0; i < z; i++) { temp = new ArrayDeque<String>(AStar(tempBoard, 50)); temp.poll(); temp.poll(); tempBoard = GUI.Threes.board.clone(); temp3 = Moves.doMove(tempBoard, temp, false); temp3.poll(); temp3.poll(); int k = 0; boolean gameon = true; while (!temp.isEmpty() && k < 5 && gameon) { nextMove = temp.pollLast(); if (nextMove.equals("L")) { gameon = GUI.Threes.Left(); } else if (nextMove.equals("R")) { gameon = GUI.Threes.Right(); } else if (nextMove.equals("U")) { gameon = GUI.Threes.Up(); } else if (nextMove.equals("D")) { gameon = GUI.Threes.Down(); } else nextMove = "X"; k++; if (!nextMove.equals("X") && gameon) { finalmoves.addFirst(nextMove); Moves.popNext(); } } // tempBoard = GUI.Threes.board.clone(); // if(!nextMove.equals("X")) // finalmoves.addFirst(nextMove); // Moves.popNext(); if (!gameon) { i = z; } } System.out.println("contents of finalmoves"); int movesize = finalmoves.size(); ArrayDeque<String> printemp = new ArrayDeque<String>(finalmoves); for (int i = 0; i < movesize; i++) { System.out.print(printemp.remove()); } System.out.println(); temp2 = Moves.doMove(board, finalmoves, true); System.out.println("heuristic score was: " + temp2.remove(0)); System.out.println("Final score was: " + temp2.remove(0)); GUI.Threes.finalBoard(); System.out.println("Move string was"); while (!temp2.isEmpty()) { System.out.print(temp2.remove()); } System.out.println(); }