// Must move to an element after add(): // it.next(); // Remove the element that was just produced: // it.remove(); // Must move to an element after remove(): // it.next(); // Change the element that was just produced: // it.set("47"); public static void testVisual(List a) { print(a); List b = new ArrayList(); fill(b); System.out.print("b = "); print(b); a.addAll(b); a.addAll(fill(new ArrayList())); print(a); // Shrink the list by removing all the elements beyond the first 1/2 of the list System.out.println(a.size()); System.out.println(a.size() / 2); // a.removeRange(a.size()/2, a.size()/2 + 2); print(a); // Insert, remove, and replace elements // using aListIterator: ListIterator x = a.listIterator(a.size() / 2); x.add("one"); print(a); System.out.println(x.next()); x.remove(); System.out.println(x.next()); x.set("47"); print(a); // Traverse the list backwards: x = a.listIterator(a.size()); while (x.hasPrevious()) System.out.print(x.previous() + " "); System.out.println(); System.out.println("testVisual finished"); }
public Object[] getChildren(Object parentElement) { if (parentElement instanceof MavenProject) { /* * Walk the hierarchy list until we find the parentElement and * return the previous element, which is the child. */ MavenProject parent = (MavenProject) parentElement; if (getProjectHierarchy().size() == 1) { // No parent exists, only one element in the tree return new Object[0]; } if (getProjectHierarchy().getFirst().equals(parent)) { // We are the final child return new Object[0]; } ListIterator<MavenProject> iter = getProjectHierarchy().listIterator(); while (iter.hasNext()) { MavenProject next = iter.next(); if (next.equals(parent)) { iter.previous(); MavenProject previous = iter.previous(); return new Object[] {previous}; } } } return new Object[0]; }
/** * Either adds a value to set or does nothing if value is already present. * * @param val Value to add. * @return The instance of value from this set or {@code null} if value was added. */ @Nullable public V addx(V val) { A.notNull(val, "val"); if (comp == null) { for (V v : vals) if (v.equals(val)) return v; vals.add(val); return null; } if (strict) { for (ListIterator<V> it = vals.listIterator(); it.hasNext(); ) { V v = it.next(); // Prefer equals to comparator. if (v.equals(val)) return v; int c = comp.compare(v, val); if (c == 0) throw new IllegalStateException("Inconsistent equals and compare methods."); if (c > 0) { // Back up. it.previous(); it.add(val); return null; } } vals.add(val); return null; } // Full scan first. for (V v : vals) if (v.equals(val)) return v; for (ListIterator<V> it = vals.listIterator(); it.hasNext(); ) { V v = it.next(); if (comp.compare(v, val) > 0) { do { // Back up. v = it.previous(); } while (comp.compare(v, val) == 0); it.add(val); return null; } } vals.add(val); return null; }
/** * (Re-)Adds the ports to the node of a component, having at least one port with a non-loop edge. * The ports are added as the direct neighbor of a port they are connected to via an edge. * * @param component The component whose ports have to get re-added. */ public void addComponentWithNonLoopEdges(final ConnectedSelfLoopComponent component) { // the node we are working on final LNode node = component.getNode(); // Set of all ports of the components that are hidden. Initially all ports that CAN be hidden. final Set<LPort> hiddenPorts = Sets.newHashSet(component.getHidablePorts()); // Iterator holding all ports that already have a portSide specified. Initially these are // all ports with an non-loop edge connected to them. While processing the elements, we will // add new ports to this Iterator. So we need a ListIterator. final ListIterator<LPort> portsWithSideIter = Lists.newLinkedList(component.getNonLoopPorts()).listIterator(); while (portsWithSideIter.hasNext()) { final LPort portWithSide = portsWithSideIter.next(); if (portWithSide.getOutgoingEdges().isEmpty()) { // inbound port for (final LEdge edgeWithHiddenPort : portWithSide.getIncomingEdges()) { final LPort hiddenPort = edgeWithHiddenPort.getSource(); if (hiddenPorts.contains(hiddenPort)) { final ListIterator<LPort> nodePortIter = node.getPorts().listIterator(); LPort portOnNode = nodePortIter.next(); // find the port with side ... while (!portOnNode.equals(portWithSide)) { portOnNode = nodePortIter.next(); } // ... and add the hidden port on it's right side nodePortIter.add(hiddenPort); portsWithSideIter.add(hiddenPort); setSideOfPort(hiddenPort, portWithSide.getSide()); // ensure the next element will be our new added element portsWithSideIter.previous(); portsWithSideIter.previous(); hiddenPorts.remove(hiddenPort); } } } else { // outbound port for (final LEdge edgeWithHiddenPort : portWithSide.getOutgoingEdges()) { final LPort hiddenPort = edgeWithHiddenPort.getTarget(); if (hiddenPorts.contains(hiddenPort)) { final ListIterator<LPort> nodePortIter = node.getPorts().listIterator(); LPort portOnNode = nodePortIter.next(); // find the port with side ... while (!portOnNode.equals(portWithSide)) { portOnNode = nodePortIter.next(); } // ... and add the hidden port on it's left side nodePortIter.previous(); nodePortIter.add(hiddenPort); portsWithSideIter.add(hiddenPort); setSideOfPort(hiddenPort, portWithSide.getSide()); // ensure the next element will be our new added element portsWithSideIter.previous(); portsWithSideIter.previous(); hiddenPorts.remove(hiddenPort); } } } } }
/** * {@inheritDoc} * * <p>This implementation first gets a list iterator that points to the end of the list (with * {@code listIterator(size())}). Then, it iterates backwards over the list until the specified * element is found, or the beginning of the list is reached. * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public int lastIndexOf(Object o) { ListIterator<E> e = listIterator(size()); if (o == null) { while (e.hasPrevious()) if (e.previous() == null) return e.nextIndex(); } else { while (e.hasPrevious()) if (o.equals(e.previous())) return e.nextIndex(); } return -1; }
/** * Restore previous unifications into variables. * * @param varsToReunify * @param saveUnifications */ private void reunify(List<Var> varsToReunify, List<Term> saveUnifications) { int size = varsToReunify.size(); ListIterator<Var> it1 = varsToReunify.listIterator(size); ListIterator<Term> it2 = saveUnifications.listIterator(size); // Only the first occurrence of a variable gets its binding saved; // following occurrences get a null instead. So, to avoid clashes // between those values, and avoid random variable deunification, // the reunification is made starting from the end of the list. while (it1.hasPrevious()) it1.previous().setLink(it2.previous()); }
public static void verify(List output, List expected) { verifyLength(output.size(), expected.size(), Test.EXACT); if (!expected.equals(output)) { // find the line of mismatch ListIterator it1 = expected.listIterator(); ListIterator it2 = output.listIterator(); while (it1.hasNext() && it2.hasNext() && it1.next().equals(it2.next())) ; throw new LineMismatchException( it1.nextIndex(), it1.previous().toString(), it2.previous().toString()); } }
private void calculateValueLists() { sequenceValues = new ArrayList<>(); timelineValues = new ArrayList<>(); final Object selectedSequenceColumn = this.sequenceColumnChooser.getSelectedItem(); if (!(selectedSequenceColumn instanceof ManyValuedAttribute)) { return; } final ManyValuedAttribute sequenceAttribute = (ManyValuedAttribute) selectedSequenceColumn; final ManyValuedAttribute timelineAttribute = (ManyValuedAttribute) timelineColumnChooser.getSelectedItem(); for (final FCAElement object : this.context.getObjects()) { Value value = this.context.getRelationship(object, sequenceAttribute); if (!sequenceValues.contains(value) && value != null) { boolean inserted = false; final ListIterator<Value> seqIt = sequenceValues.listIterator(); while (seqIt.hasNext()) { final Value curValue = seqIt.next(); if (value.isLesserThan(curValue)) { if (seqIt.hasPrevious()) { seqIt.previous(); } seqIt.add(value); inserted = true; break; } } if (!inserted) { seqIt.add(value); } } value = this.context.getRelationship(object, timelineAttribute); if (!timelineValues.contains(value) && value != null) { boolean inserted = false; final ListIterator<Value> tlIt = timelineValues.listIterator(); while (tlIt.hasNext()) { final Value curValue = tlIt.next(); if (curValue != null && value.isLesserThan(curValue)) { if (tlIt.hasPrevious()) { tlIt.previous(); } tlIt.add(value); inserted = true; break; } } if (!inserted) { tlIt.add(value); } } } }
@TrackedGetterTest @Test public void testListIterator_index() { addToDelegate(); @SuppressWarnings("unchecked") ListIterator<Object> iter = fixture.listIterator(delegate.size()); assertThat(iter.hasPrevious(), is(true)); assertThat(iter.previous(), is((Object) "Dave")); assertThat(iter.hasPrevious(), is(true)); assertThat(iter.previous(), is((Object) "Cathy")); }
public void testIterator() { List<Integer> list = Arrays.asList(1, 2, 3, 4); ListIterator<Integer> i = new FilteringListIterator<Integer>( list.listIterator(), new Filter<Integer>() { public boolean accept(Integer i) { return i % 2 == 1; } }); assertEquals(0, i.nextIndex()); assertEquals(-1, i.previousIndex()); assertTrue(i.hasNext()); assertEquals(new Integer(1), i.next()); checkNextPrevious(i, true, true); assertEquals(1, i.nextIndex()); assertEquals(0, i.previousIndex()); assertEquals(new Integer(3), i.next()); checkNextPrevious(i, false, true); assertEquals(2, i.nextIndex()); assertEquals(1, i.previousIndex()); assertEquals(new Integer(3), i.previous()); checkNextPrevious(i, true, true); assertEquals(1, i.nextIndex()); assertEquals(0, i.previousIndex()); assertEquals(new Integer(3), i.next()); checkNextPrevious(i, false, true); assertEquals(2, i.nextIndex()); assertEquals(1, i.previousIndex()); assertEquals(new Integer(3), i.previous()); checkNextPrevious(i, true, true); assertEquals(1, i.nextIndex()); assertEquals(0, i.previousIndex()); assertEquals(new Integer(1), i.previous()); checkNextPrevious(i, true, false); assertEquals(0, i.nextIndex()); assertEquals(-1, i.previousIndex()); try { i.previous(); fail(); } catch (NoSuchElementException e) { // ok } }
private <E> E resetListIterator(ListIterator<E> l) throws NoSuchElementException { if (l.hasPrevious()) { E temp = l.previous(); return temp; } else { E start = null; while (l.hasNext()) { start = l.next(); } l.previous(); return start; } }
@Override protected void onDraw(final Canvas canvas) { super.onDraw(canvas); if (profile == null) { return; } final int width = getWidth(); final int height = getHeight(); canvas.drawRect(0, 0, width, height, bgPaint); final float xStep = width / GRID_X; final float yStep = height / GRID_Y; int cIndex = 0; ListIterator<Region> regions = profile.regions(false); while (regions.hasPrevious()) { final Region region = regions.previous(); final RectF r = region.getActualRect(width, height); rPaint.setColor(COLORS[cIndex]); rPaint.setAlpha(0x80); canvas.drawRect(r, rPaint); cIndex = (cIndex + 1) % COLORS.length; } drawGrid(canvas, xStep, yStep); cIndex = 0; regions = profile.regions(false); while (regions.hasPrevious()) { final Region region = regions.previous(); final RectF r = region.getActualRect(width, height); rPaint.setColor(COLORS[cIndex]); drawBounds(canvas, r, rPaint); cIndex = (cIndex + 1) % COLORS.length; } if (current != null) { rPaint.setColor(Color.WHITE); rPaint.setAlpha(0x80); final RectF r = current.getActualRect(width, height); canvas.drawRect(r, rPaint); rPaint.setColor(Color.WHITE); drawBounds(canvas, r, rPaint); } }
@Override public void parse(String start, ListIterator<String> iterator) { if (myIgnoreMode) { return; } if (!iterator.hasNext()) { mySyntaxException = new PatchSyntaxException(iterator.previousIndex(), "Empty additional info header"); return; } while (true) { final String header = iterator.next(); final int idxHead = header.indexOf(UnifiedDiffWriter.ADD_INFO_HEADER); if (idxHead == -1) { if (myAddMap.isEmpty()) { mySyntaxException = new PatchSyntaxException(iterator.previousIndex(), "Empty additional info header"); } iterator.previous(); return; } final String subsystem = header.substring(idxHead + UnifiedDiffWriter.ADD_INFO_HEADER.length()).trim(); if (!iterator.hasNext()) { mySyntaxException = new PatchSyntaxException( iterator.previousIndex(), "Empty '" + subsystem + "' data section"); return; } final StringBuilder sb = new StringBuilder(); myAddMap.put(subsystem, sb); while (iterator.hasNext()) { final String line = iterator.next(); if (!line.startsWith(UnifiedDiffWriter.ADD_INFO_LINE_START)) { iterator.previous(); break; } if (sb.length() > 0) { sb.append("\n"); } sb.append( StringUtil.unescapeStringCharacters( line.substring(UnifiedDiffWriter.ADD_INFO_LINE_START.length()))); } } }
public LinkedList<MapLocation> pathFind(MapLocation start, MapLocation target) throws GameActionException { // for (int i = 0; i < myRobot.allies.length; i++) { // RobotInfo r = rc.senseRobotInfo(myRobot.allies[i]); // if (myRobot.allies[i].getID() == myRobot.ID) continue; // map[r.location.x][r.location.y] = -2; // } // for (int i = 0; i < myRobot.enemies.length; i++) { // RobotInfo r = rc.senseRobotInfo(myRobot.enemies[i]); // map[r.location.x][r.location.y] = -2; // } int x = Clock.getRoundNum(); SearchNode bugSearch = bugSearch(start, target); SearchNode[] nodes = new SearchNode[bugSearch.length]; int counter = bugSearch.length - 1; while (bugSearch.prevLoc != null) { nodes[counter] = bugSearch; bugSearch = bugSearch.prevLoc; counter--; } nodes[0] = bugSearch; LinkedList<MapLocation> pivots = new LinkedList<MapLocation>(); pivots.add(nodes[0].loc); for (int i = 1; i < nodes.length; i++) { if (nodes[i].isPivot) { pivots.add(nodes[i].loc); } } counter = 0; ListIterator<MapLocation> li1 = pivots.listIterator(), li2; while (li1.hasNext()) { li2 = pivots.listIterator(pivots.size()); while (li2.hasPrevious() && li2.previousIndex() > li1.nextIndex() + 1) { if (canTravel(li1.next(), li2.previous())) { pivots.subList(li1.nextIndex(), li2.previousIndex() + 1).clear(); li1 = pivots.listIterator(++counter); break; } li1.previous(); } li1.next(); } if (false) System.out.println(Clock.getRoundNum() - x); return pivots; }
private List<ChatMessage> sanitizeMap(final SortedMap<Date, ChatMessage> aMap) { if (aMap.isEmpty() || aMap.size() == 1) return Lists.newArrayList(aMap.values()); final LinkedList<ChatMessage> ret = Lists.newLinkedList(aMap.values()); final ListIterator<ChatMessage> i = ret.listIterator(); ChatMessage prevMsg = i.next(); do { ChatMessage msg = i.next(); if (!msg.getPreviousMessageDate().equals(prevMsg.getDate())) { if (msg.getPreviousMessageDate().before(prevMsg.getDate())) { msg.setPreviousMessageDate(prevMsg.getDate()); } else { final ChatMessage tmp = createLostMessageBetween( msg.getRoom(), prevMsg.getDate(), msg.getPreviousMessageDate()); aMap.put(tmp.getDate(), tmp); i.previous(); i.add(tmp); i.next(); msg = tmp; } } prevMsg = msg; } while (i.hasNext()); return ret; }
/** * Returns the last index of the given element. * * @param o the array/list of objects to examine, or a string. * @since 5.0.7 */ public static final int lastIndexOf(Object o, Object element) { if (o instanceof String) { return element instanceof String ? ((String) o).lastIndexOf((String) element) : -1; } else if (o instanceof List) { int j = ((List) o).size(); for (ListIterator it = ((List) o).listIterator(j); it.hasPrevious(); j--) if (Objects.equals(it.previous(), element)) return j - 1; } else if (o instanceof Object[]) { final Object[] ary = (Object[]) o; for (int j = ary.length; --j >= 0; ) if (Objects.equals(ary[j], element)) return j; } else if (o instanceof int[]) { if (element instanceof Number) { int v = ((Number) element).intValue(); final int[] ary = (int[]) o; for (int j = ary.length; --j >= 0; ) if (ary[j] == v) return j; } } else if (o instanceof long[]) { if (element instanceof Number) { long v = ((Number) element).longValue(); final long[] ary = (long[]) o; for (int j = ary.length; --j >= 0; ) if (ary[j] == v) return j; } } else if (o instanceof short[]) { if (element instanceof Number) { short v = ((Number) element).shortValue(); final short[] ary = (short[]) o; for (int j = ary.length; --j >= 0; ) if (ary[j] == v) return j; } } else if (o instanceof byte[]) { if (element instanceof Number) { byte v = ((Number) element).byteValue(); final byte[] ary = (byte[]) o; for (int j = ary.length; --j >= 0; ) if (ary[j] == v) return j; } } else if (o instanceof double[]) { if (element instanceof Number) { double v = ((Number) element).doubleValue(); final double[] ary = (double[]) o; for (int j = ary.length; --j >= 0; ) if (Double.compare(ary[j], v) == 0) return j; } } else if (o instanceof float[]) { if (element instanceof Number) { float v = ((Number) element).floatValue(); final float[] ary = (float[]) o; for (int j = ary.length; --j >= 0; ) if (Float.compare(ary[j], v) == 0) return j; } } else if (o instanceof char[]) { char v; if (element instanceof Character) v = ((Character) element).charValue(); else if (element instanceof String && ((String) element).length() > 0) v = ((String) element).charAt(0); else return -1; final char[] ary = (char[]) o; for (int j = ary.length; --j >= 0; ) if (ary[j] == v) return j; } else if (o != null) { throw new IllegalArgumentException("Unknown object for indexOf: " + o.getClass()); } return -1; }
/** * Merges the view states contained in the given list into a single view. <br> * The view is the concatenation of the different views, according to the order provided by the * list itself. The version is the smallest all the versions. * * @param l A list conatining the view states to merge * @return the merged view state. * @throws AppiaGroupException See {@linkplain ViewState#ViewState(String, Group, ViewID, * ViewID[], Endpt[], InetWithPort[])} * @throws NullPointerException See {@linkplain ViewState#ViewState(String, Group, ViewID, * ViewID[], Endpt[], InetWithPort[])} */ public static ViewState merge(List l) throws NullPointerException, AppiaGroupException { ListIterator iter = l.listIterator(l.size()); int viewsize = 0; int prevsize = 0; while (iter.hasPrevious()) { ViewState aux = (ViewState) iter.previous(); viewsize += aux.view.length; prevsize += aux.previous.length; } String v = null; Group g = null; ViewID vid = null; ViewID[] prevs = new ViewID[prevsize]; Endpt[] endpts = new Endpt[viewsize]; InetSocketAddress[] addrs = new InetSocketAddress[viewsize]; int iprevs = 0, iendpts = 0, iaddrs = 0; while (iter.hasNext()) { ViewState aux = (ViewState) iter.next(); if ((v == null) || (aux.version.compareTo(v) < 0)) v = aux.version; if (g == null) g = aux.group; if (vid == null) vid = aux.id; else if (aux.id.ltime > vid.ltime) vid.ltime = aux.id.ltime; System.arraycopy(aux.previous, 0, prevs, iprevs, aux.previous.length); iprevs += aux.previous.length; System.arraycopy(aux.view, 0, endpts, iendpts, aux.view.length); iendpts += aux.view.length; System.arraycopy(aux.addresses, 0, addrs, iaddrs, aux.addresses.length); iaddrs += aux.addresses.length; } return new ViewState(v, g, vid, prevs, endpts, addrs); }
public static void main(String[] args) { Scanner teclado = new Scanner(System.in); String nombre, pregunta; boolean continuar = true; ArrayList<String> cadenaNombres = new ArrayList<String>(); do { System.out.println("Introduce el nombre: "); nombre = teclado.next(); cadenaNombres.add(nombre); do { System.out.println("¿Quiere insertar otro nombre?(n|s)"); pregunta = teclado.next(); if (pregunta.equals("n")) continuar = false; else if (pregunta.equals("s")) continuar = true; } while (!pregunta.equals("s") && !pregunta.equals("n")); } while (continuar); ListIterator<String> ite = cadenaNombres.listIterator(); System.out.println("Orden introducidos: "); while (ite.hasNext()) { System.out.println(ite.next()); } System.out.println(); System.out.println("Contrario: "); while (ite.hasPrevious()) { System.out.println(ite.previous()); } }
private Column undeclaredHKeyColumn(HKeyColumn hKeyColumn) { Column undeclaredHKeyColumn = null; int rootMostDepth = rootMostTable().getDepth(); List<Column> equivalentColumns = hKeyColumn.equivalentColumns(); switch (getJoinType()) { case LEFT: // use a rootward bias, but no more rootward than the rootmost table for (Column equivalentColumn : equivalentColumns) { int equivalentColumnDepth = equivalentColumn.getTable().getDepth(); if (undeclaredHKeyColumn == null && equivalentColumnDepth >= rootMostDepth) { undeclaredHKeyColumn = equivalentColumn; } } break; case RIGHT: // use a leafward bias, but no more leafward than the leafdmost table int leafMostDepth = leafMostTable().getDepth(); for (ListIterator<Column> reverseCols = equivalentColumns.listIterator(equivalentColumns.size()); reverseCols.hasPrevious(); ) { Column equivalentColumn = reverseCols.previous(); int equivalentColumnDepth = equivalentColumn.getTable().getDepth(); if (undeclaredHKeyColumn == null && equivalentColumnDepth <= leafMostDepth) { undeclaredHKeyColumn = equivalentColumn; } } break; } if (undeclaredHKeyColumn == null) { undeclaredHKeyColumn = hKeyColumn.column(); } return undeclaredHKeyColumn; }
// Итеративна имплементација на DFS со ограничена длабочина на пребарување - вториот параметар // depth public boolean iterativeLDDFS(Comparable value, int depth) { Stack<TreeNode> stack = new Stack<TreeNode>(); // Иницијализација на празен стек за јазлите на дрвото TreeNode state = root; // Првично, моменталната состојба е коренот на дрвото while (true) { // Циклус кој не завршува освен ако не е прекинат одвнатре if (state.getValue().compareTo(value) == 0) return true; // true ако моменталната состојба е бараната else if (state.hasChildren() && state.depth() < depth) { // Ако моменталната состојба не е бараната и ако нејзината длабочина е // помала од максималната дозволена... ListIterator<TreeNode> iter = state .getChildren() .listIterator( state .getChildren() .size()); // се иницијализира итератор кој тргнува од последното дете на // моменталната состојба while (iter.hasPrevious()) stack.push(iter.previous()); // Стекот се полни со децата на моменталната состојба } if (stack.empty()) return false; // Ако стекот останал празен, се враќа false, односно бараната вредност не е // пронајдена state = stack.pop(); // Ако во стекот останале јазли, се вади последно ставениот како моментална // состојба и се продолжува со него } }
@Override public boolean incrementToken() throws IOException { while (!done && queue.size() < windowSize) { if (!input.incrementToken()) { done = true; break; } // reverse iterating for better efficiency since we know the // list is already sorted, and most token start offsets will be too. ListIterator<OrderedToken> iter = queue.listIterator(queue.size()); while (iter.hasPrevious()) { if (offsetAtt.startOffset() >= iter.previous().startOffset) { // insertion will be before what next() would return (what // we just compared against), so move back one so the insertion // will be after. iter.next(); break; } } OrderedToken ot = new OrderedToken(); ot.state = captureState(); ot.startOffset = offsetAtt.startOffset(); iter.add(ot); } if (queue.isEmpty()) { return false; } else { restoreState(queue.removeFirst().state); return true; } }
public void rollback() throws IllegalStateException { try { if (state == NO_TXN || state == ROLLED_BACK) { throw new IllegalStateException("Transaction is not active"); } checkThread(); state = ROLLING_BACK; try { rollbackTxBackup(); final List<Future> futures = new ArrayList<Future>(txLogs.size()); final ListIterator<TransactionLog> iter = txLogs.listIterator(txLogs.size()); while (iter.hasPrevious()) { final TransactionLog txLog = iter.previous(); futures.add(txLog.rollback(nodeEngine)); } for (Future future : futures) { try { future.get(ROLLBACK_TIMEOUT_MINUTES, TimeUnit.MINUTES); } catch (Throwable e) { nodeEngine.getLogger(getClass()).warning("Error during rollback!", e); } } // purge tx backup purgeTxBackups(); } catch (Throwable e) { throw ExceptionUtil.rethrow(e); } finally { state = ROLLED_BACK; } } finally { setThreadFlag(null); } }
// Итеративна имплементација на DBFS. public boolean iterativeIDDFS(Comparable value) { Stack<TreeNode> stack = new Stack<TreeNode>(); int maxDepth = this.maxDepth(), depth = 0; while (depth <= maxDepth) { // Циклусја зголемува длабочината до која се пребарува TreeNode state = root; // DFS се иницијализира почетно на коренот на дрвото while (true) { // обичен DFS со ограничена длабочина if (state.getValue().compareTo(value) == 0) return true; // true - бараната состојба else if (state.hasChildren() && state.depth() < depth) { // Во случај да не е бараната состојба, се проверува дали моменталната // има деца и дали нејзината длабочина е дозволена во моменталната // итерација на DFS ListIterator<TreeNode> iter = state .getChildren() .listIterator( state .getChildren() .size()); // Иницијализација на итератор кој тргнува од последното дете на // листата од деца на моменталната состојба while (iter.hasPrevious()) stack.push(iter.previous()); // Ставање на децата на моменталната состојба на стек } if (stack.empty()) break; // Ако стекот е празен, доаѓа до завршување на моменталната итерација на DFS state = stack.pop(); // Ако има елементи во стекот, се вади последно ставениот елемент } depth++; // На крајот од секоја итерација на DFS, се зголемува длабочината до која се // пребарува } return false; // Ако методата излегла од надворешниот циклус без да врати решение, значи дека // решение не постои и се враќа false }
/** * Look ahead at the next measure, build and determine a suitable SongPhrase to handle it. * * @param itM an iterator over the measures collection. It must be pointing so that itM.next() * returns the current measure, which will be marked as a repeatStart. * @param itMTP an iterator over the measure-track pairs collection. It must be pointing so that * itMTP.next() returns the first track of the current measure * @param tracks The tracks definitions * @return the next SongPhrase */ private static SongPhrase phraseFactory( Song song, ListIterator<GPMeasure> itM, ListIterator<GPMeasureTrackPair> itMTP, List<GPTrack> tracks) throws GPFormatException { SongPhrase sp = null; GPMeasure measure = itM.next(); // peek inside the measure // and dispatch to the right // factory itM.previous(); // rewind before calling the right factory method // TODO add getter and setter for GP4Measure.repeatStart logger.finer("Measure " + measure.getNumber() + " repeat start " + measure.repeatStart); logger.finer( "Measure " + measure.getNumber() + " repeat count " + measure.getNumberOfRepetitions()); // if it's the start of a repeat, then make a repeated phrase if (measure.repeatStart) { logger.fine("Creating a repeated phrase at " + measure.getNumber()); sp = makeRepeatedSongPhrase(song, itM, itMTP, tracks); } // Failing everything else, just return a single measure if (sp == null) { logger.fine("Creating a measure phrase at " + measure.getNumber()); sp = makeSongMeasure(song, itM, itMTP, tracks); } return sp; }
/** * Merges any number of sorted lists of elements into a given list using a custom comparator in * linear time O(N) where N is the sum of each lists' size, asumming all input lists can be * iterated in linear time. * * <p>The elements will be added to the end of the {@code target} list. * * <p>NOTE: any elements previoulsy existing in target won't be modified or reordered in any way. * * @param sources the sorted lists to be merged. they should be sorted by the natural order of the * type T (i.e. T.compareTo(T)) * @param target the list where the elements will be inserted respecting their natural order. * @param comparator the comparator that provides the order for this merge operation */ public static <T> void mergeLists( List<? extends List<? extends T>> sources, List<? super T> target, Comparator<? super T> comparator) { int size = 0; List<ListIterator<? extends T>> iterators = new ArrayList<ListIterator<? extends T>>(sources.size()); for (List<? extends T> source : sources) { size += source.size(); iterators.add(source.listIterator()); } for (int i = 0; i < size; i++) { T min = null; int minIndex = -1; for (int j = 0; j < iterators.size(); j++) { ListIterator<? extends T> it = iterators.get(j); if (it.hasNext()) { T t = it.next(); if (minIndex == -1 || comparator.compare(t, min) < 0) { minIndex = j; min = t; } it.previous(); } } target.add(min); iterators.get(minIndex).next(); } }
protected void processUses(FunctionStmtToken result, ListIterator<Token> iterator) { Token next = nextToken(iterator); if (next instanceof NamespaceUseStmtToken) { next = nextToken(iterator); if (!isOpenedBrace(next, BraceExprToken.Kind.SIMPLE)) unexpectedToken(next, "("); List<ArgumentStmtToken> arguments = new ArrayList<ArgumentStmtToken>(); while (iterator.hasNext()) { ArgumentStmtToken argument = processArgument(iterator); if (argument == null) break; if (argument.getValue() != null) unexpectedToken(argument.getValue().getSingle()); arguments.add(argument); FunctionStmtToken parent = analyzer.getFunction(true); if (parent != null) { parent.variable(argument.getName()).setUsed(true); if (argument.isReference()) { parent.variable(argument.getName()).setPassed(true).setUnstable(true); } parent = analyzer.peekClosure(); if (parent != null) { parent.variable(argument.getName()).setUnstable(true); } } } result.setUses(arguments); } else { result.setUses(new ArrayList<ArgumentStmtToken>()); iterator.previous(); } }
@Override void getOperationDescriptions( final ListIterator<PathElement> iterator, final Map<String, OperationEntry> providers, final boolean inherited) { if (!iterator.hasNext()) { checkPermission(); providers.putAll(operationsUpdater.get(this)); if (inherited) { getInheritedOperations(providers, true); } return; } final PathElement next = iterator.next(); try { final String key = next.getKey(); final Map<String, NodeSubregistry> snapshot = childrenUpdater.get(this); final NodeSubregistry subregistry = snapshot.get(key); if (subregistry != null) { subregistry.getHandlers(iterator, next.getValue(), providers, inherited); } } finally { iterator.previous(); } }
/** * Prepare the geometries for rendering. This must be done before calling <code>render()</code>! * This recursively calls generate() on the OMGeometries on the list. * * @param p a <code>Projection</code> * @param forceProjectAll if true, all the geometries on the list are generated with the new * projection. If false they are only generated if getNeedToRegenerate() returns true * @see OMGeometry#generate * @see OMGeometry#regenerate */ public boolean generate(Projection p, boolean forceProjectAll) { setNeedToRegenerate(true); GeneralPath projectedShape = null; synchronized (graphics) { if (traverseMode == FIRST_ADDED_ON_TOP) { ListIterator<OMGeometry> iterator = graphics.listIterator(size()); while (iterator.hasPrevious()) { projectedShape = updateShape(projectedShape, (OMGeometry) iterator.previous(), p, forceProjectAll); } } else { ListIterator<OMGeometry> iterator = graphics.listIterator(); while (iterator.hasNext()) { projectedShape = updateShape(projectedShape, (OMGeometry) iterator.next(), p, forceProjectAll); } } } setShape(projectedShape); setLabelLocation(projectedShape, p); setNeedToRegenerate(false); return projectedShape != null; }
/* Creates a parent chain of ResourceMaps for the specfied * ResourceBundle names. One ResourceMap is created for each * subsequence of ResourceBundle names with a common bundle * package name, i.e. with a common resourcesDir. The parent * of the final ResourceMap in the chain is root. */ private ResourceMap createResourceMapChain( ClassLoader cl, ResourceMap root, ListIterator<String> names) { if (!names.hasNext()) { return root; } else { List<String> rmNames = new ArrayList<String>(2); String bundleName0 = names.next(); String rmBundlePackage = bundlePackageName(bundleName0); rmNames.add(bundleName0); while (names.hasNext()) { String bundleName = names.next(); String bpn = bundlePackageName(bundleName); if (rmBundlePackage.equals(bpn)) { rmNames.add(bundleName); } else { names.previous(); break; } } ResourceMap parent = createResourceMapChain(cl, root, names); return createResourceMap(cl, parent, rmNames); } }
private static void reverseItemList(List<String> itemList) { ListIterator<String> iter = itemList.listIterator(itemList.size()); while (iter.hasPrevious()) { System.out.printf("%s ", iter.previous()); } System.out.println(); }