// 私有函数,广度优先遍历 private void broadFirstSearch(boolean[] isVisited, int i) { int u, w; LinkedList queue = new LinkedList(); // 访问结点i System.out.print(getValueByIndex(i) + " "); isVisited[i] = true; // 结点入队列 queue.addLast(i); while (!queue.isEmpty()) { u = ((Integer) queue.removeFirst()).intValue(); w = getFirstNeighbor(u); while (w != -1) { if (!isVisited[w]) { // 访问该结点 System.out.print(getValueByIndex(w) + " "); // 标记已被访问 isVisited[w] = true; // 入队列 queue.addLast(w); } // 寻找下一个邻接结点 w = getNextNeighbor(u, w); } } }
private boolean addItem(LinkedList<ItemInfo> items, ItemInfo itemInfo) { boolean added = false; int idx = items.indexOf(itemInfo); if (idx != -1) { // HACK: Always swap existing ItemInfos with our new one, since it will // more up-to-date information ItemInfo existing = items.set(idx, itemInfo); assert (existing != null); return (true); } if (itemInfo.hasCurrentPrice()) assert (itemInfo.getCurrentPrice() > 0) : "Negative current price for " + itemInfo; // If we have room, shove it right in // We'll throw it in the back because we know it hasn't been used yet if (items.size() < AuctionMarkConstants.ITEM_ID_CACHE_SIZE) { items.addLast(itemInfo); added = true; // Otherwise, we can will randomly decide whether to pop one out } else if (this.rng.nextBoolean()) { items.pop(); items.addLast(itemInfo); added = true; } return (added); }
void mixLists( LinkedList<Integer> left, LinkedList<Integer> right, ArrayList<LinkedList<Integer>> mix, LinkedList<Integer> before) { if (before.isEmpty() || right.isEmpty()) { LinkedList<Integer> l = new LinkedList<>(); l = (LinkedList<Integer>) before.clone(); l.addAll(left); l.addAll(right); mix.add(l); return; } int hl = left.removeFirst(); before.addLast(hl); mixLists(left, right, mix, before); before.removeLast(); left.addFirst(hl); int hr = right.removeFirst(); before.addLast(hr); mixLists(left, right, mix, before); before.removeLast(); right.addFirst(hr); }
public synchronized HandleStatus handle(final MessageReference reference) { if (statusToReturn == HandleStatus.BUSY) { return HandleStatus.BUSY; } if (filter != null) { if (filter.match(reference.getMessage())) { references.addLast(reference); reference.getQueue().referenceHandled(); notify(); return HandleStatus.HANDLED; } else { return HandleStatus.NO_MATCH; } } if (newStatus != null) { if (delayCountdown == 0) { statusToReturn = newStatus; newStatus = null; } else { delayCountdown--; } } if (statusToReturn == HandleStatus.HANDLED) { reference.getQueue().referenceHandled(); references.addLast(reference); notify(); } return statusToReturn; }
/** * process a task multi threaded synchronized by the internal task queue. The task will be * processed by a dedicated thread. The given worker pool <i>can</i> be used to perform this tasks * (as well as other task of the queue). * * @param task the task to process * @param workerpool the workerpool */ public void performMultiThreaded(Runnable task, Executor workerpool) { // add task to queue synchronized (multithreadedTaskQueue) { // (Multithreaded) worker is not running if (multithreadedTaskQueue.isEmpty()) { multithreadedTaskQueue.addLast(task); try { workerpool.execute(multithreadedTaskProcessor); } catch (RejectedExecutionException ree) { if (LOG.isLoggable(Level.FINE)) { LOG.fine( "task has been rejected by worker pool " + workerpool + " (worker pool cosed?) performing task by starting a new thread"); } Thread t = new Thread(multithreadedTaskProcessor, "SerializedTaskQueueFallbackThread"); t.setDaemon(true); t.start(); } } else { multithreadedTaskQueue.addLast(task); } } }
/* *(non-Javadoc) * @see android.widget.AdapterView#setSelection(int) */ @Override public void setSelection(int position) { mNextScreen = INVALID_SCREEN; mScroller.forceFinished(true); if (mAdapter != null) { position = Math.max(position, 0); position = Math.min(position, mAdapter.getCount() - 1); recycleViews(); View currentView = makeAndAddView(position, true); mLoadedViews.addLast(currentView); for (int offset = 1; mBufferedItemCount - offset >= 0; offset++) { int leftIndex = position - offset; int rightIndex = position + offset; if (leftIndex >= 0) { mLoadedViews.addFirst(makeAndAddView(leftIndex, false)); } if (rightIndex < mAdapter.getCount()) { mLoadedViews.addLast(makeAndAddView(rightIndex, true)); } } mCurrentBufferIndex = mLoadedViews.indexOf(currentView); mCurrentAdapterIndex = position; requestLayout(); setVisibleView(mCurrentBufferIndex, false); if (viewSwitchListener != null) { viewSwitchListener.onSwitched(currentView, mCurrentAdapterIndex); } } }
protected void add( boolean list, boolean warning, int type, String text, BaseNode b, BranchNode ba, BranchNode bb) { ConflictEntry ce = new ConflictEntry(); ce.text = text; ce.type = type; ce.b = b; // let b1=left and b2=right if (ba == null) { ba = bb; bb = null; } if (ba != null && ba.isLeftTree()) { ce.b1 = ba; ce.b2 = bb; } else { ce.b1 = bb; ce.b2 = ba; } if (list) { ce.mergePath = pt.getPathString(); } else ce.mergePath = pt.getFullPathString(); if (warning) warnings.addLast(ce); else conflicts.addLast(ce); }
public static void postOrderNoIn(TreeNode root) { if (root == null) return; LinkedList<TreeNode> stack = new LinkedList<>(); LinkedList<Boolean> flag = new LinkedList<>(); boolean curFlag; while (!stack.isEmpty() || root != null) { while (root != null) { stack.addLast(root); flag.addLast(true); root = root.left; } root = stack.getLast(); curFlag = flag.getLast(); flag.removeLast(); if (curFlag) { // flag.addLast(false); root = root.right; } else { stack.removeLast(); System.out.print(root.val + " "); root = null; // 第一次的时候缺少这一句,陷入死循环。 } } }
public void weavelists( LinkedList<Integer> first, LinkedList<Integer> second, ArrayList<LinkedList<Integer>> results, LinkedList<Integer> prefix) { if (first.size() == 0 || second.size() == 0) { LinkedList<Integer> result = (LinkedList<Integer>) prefix.clone(); result.addAll(first); result.addAll(second); results.add(result); return; } int headFirst = first.removeFirst(); prefix.addLast(headFirst); weavelists(first, second, results, prefix); prefix.removeLast(); first.addFirst(headFirst); int secondHead = second.removeFirst(); prefix.addLast(secondHead); weavelists(first, second, results, prefix); prefix.removeLast(); second.addFirst(secondHead); }
/** * Constructs a path to a given node, for a given set of predecessors. The result is a list of * alternating Node/Relationship. * * @param node The start node * @param predecessors The predecessors set * @param includeNode Boolean which determines if the start node should be included in the paths * @param backwards Boolean, if true the order of the nodes in the paths will be reversed * @return A path as a list of alternating Node/Relationship. */ public static List<PropertyContainer> constructSinglePathToNode( Node node, Map<Node, List<Relationship>> predecessors, boolean includeNode, boolean backwards) { LinkedList<PropertyContainer> path = new LinkedList<PropertyContainer>(); if (includeNode) { if (backwards) { path.addLast(node); } else { path.addFirst(node); } } Node currentNode = node; List<Relationship> currentPreds = predecessors.get(currentNode); // Traverse predecessors until we have added a node without predecessors while (currentPreds != null && currentPreds.size() != 0) { // Get next node Relationship currentRelationship = currentPreds.get(0); currentNode = currentRelationship.getOtherNode(currentNode); // Add current if (backwards) { path.addLast(currentRelationship); path.addLast(currentNode); } else { path.addFirst(currentRelationship); path.addFirst(currentNode); } // Continue with the next node currentPreds = predecessors.get(currentNode); } return path; }
public static void main(String[] args) throws Exception { // explicit configuration for (int i = 0; i < PDGs.pdgs.length; i++) { String file = PDGs.pdgs[i]; /* 1 */ g = SDG.readFrom(file); ThreadInstance ti = g.getThreadsInfo().iterator().next(); LinkedList<ThreadInstance> l = new LinkedList<ThreadInstance>(); l.add(ti); ThreadsInformation info = new ThreadsInformation(l); g.setThreadsInfo(info); int[] threads = new int[] {0}; for (SDGNode n : g.vertexSet()) { n.setThreadNumbers(threads); } System.out.println("initializing the slicers"); LinkedList<Slicer> array = new LinkedList<Slicer>(); array.addLast(new SummarySlicerBackward(g)); array.addLast(new Phase1SlicerBackward(g)); System.out.println(file); System.out.println("criteria: " + g.vertexSet().size()); String str = compare(array, g.vertexSet()); System.out.println(str); } }
@Override protected void processDelivery(Delivery delivery) { final MessageDelivery md = (MessageDelivery) delivery.getContext(); if (delivery.remotelySettled()) { if (delivery.getTag().length > 0) { checkinTag(delivery.getTag()); } final DeliveryState state = delivery.getRemoteState(); if (state == null || state instanceof Accepted) { if (!delivery.remotelySettled()) { delivery.disposition(new Accepted()); } } else if (state instanceof Rejected) { // re-deliver /w incremented delivery counter. md.delivery = null; md.incrementDeliveryCount(); outbound.addLast(md); } else if (state instanceof Released) { // re-deliver && don't increment the counter. md.delivery = null; outbound.addLast(md); } else if (state instanceof Modified) { Modified modified = (Modified) state; if (modified.getDeliveryFailed()) { // increment delivery counter.. md.incrementDeliveryCount(); } } delivery.settle(); } md.fireWatches(); }
protected void setUp() throws Exception { carreras = new LinkedList<Carrera>(); for (int j = 0; j < CANTIDAD_CARRERAS; j++) { Carrera carrera = new Carrera(new ReglamentoValeTodo()); for (int i = 0; i < CANTIDAD_PARTICIPANTES; i++) { Participante participante = new Participante(new Caballo(), new Jockey(), carrera); carrera.addParticipante(participante); } carreras.add(carrera); } LinkedList<Participante> participantesApostados = new LinkedList<Participante>(); participantesApostados.addLast(carreras.get(0).getParticipantes().get(0)); participantesApostados.addLast(carreras.get(1).getParticipantes().get(0)); participantesApostados.addLast(carreras.get(2).getParticipantes().get(0)); participantesApostados.addLast(carreras.get(3).getParticipantes().get(0)); apuesta1 = ApuestaFactory.getInstance() .crear(ApuestaCuaterna.class, participantesApostados, MONTO_APUESTA); participantesApostados = new LinkedList<Participante>(); participantesApostados.addLast(carreras.get(0).getParticipantes().get(0)); participantesApostados.addLast(carreras.get(1).getParticipantes().get(2)); participantesApostados.addLast(carreras.get(2).getParticipantes().get(0)); participantesApostados.addLast(carreras.get(3).getParticipantes().get(1)); apuesta2 = ApuestaFactory.getInstance() .crear(ApuestaCuaterna.class, participantesApostados, MONTO_APUESTA); }
public static String obfuscate(String email) { LinkedList<String> emailList = new LinkedList<>(); // Attack the dots String[] chunks = email.split(Pattern.quote(".")); String[] atChunks = null; int dotCounter = chunks.length - 1; for (int i = 0; i < chunks.length; i++) { emailList.addLast(chunks[i]); if (dotCounter != 0) { emailList.addLast("[.]"); dotCounter--; } } // Attack the @ for (int j = 0; j < emailList.size(); j++) { if (emailList.get(j).contains("@")) { atChunks = emailList.get(j).split(Pattern.quote("@")); emailList.remove(j); emailList.add(j, atChunks[0]); emailList.add(j + 1, "[at]"); emailList.add(j + 2, atChunks[1]); } } System.out.println(toString(emailList)); return toString(emailList); }
private void buildValuePermutation() { for (int i = 0; i < inputValues.size(); i++) { LinkedList<String> lst2 = new LinkedList<String>(inputValues); lst2.remove(i); for (int j = 0; j < lst2.size(); j++) { LinkedList<String> lst3 = new LinkedList<String>(lst2); lst3.remove(j); for (int k = 0; k < lst3.size(); k++) { LinkedList<String> lst4 = new LinkedList<String>(lst3); lst4.remove(k); for (int l = 0; l < lst4.size(); l++) { LinkedList<String> rslt = new LinkedList<String>(); rslt.addLast(inputValues.get(i)); rslt.addLast(lst2.get(j)); rslt.addLast(lst3.get(k)); rslt.addLast(lst4.get(l)); permutations.add(rslt); } } } } }
public void print() { int height = height(); // System.out.println("height of tree: "+height); // System.out.println(); if (height == 0) return; int distance = 2; int offset = distance * height; LinkedList<Node> nodeList = new LinkedList<Node>(); nodeList.addLast(root); int hIdx = 0; while (!nodeList.isEmpty()) { int size = nodeList.size(); int innerOffset = offset; for (Node node : nodeList) { System.out.printf("%" + innerOffset + "s", node.data); innerOffset += distance * hIdx; } System.out.println(); hIdx++; offset = offset - distance; for (int i = 0; i < size; i++) { Node node = nodeList.poll(); if (node.left != null) nodeList.addLast(node.left); if (node.right != null) nodeList.addLast(node.right); } } }
/** * Return a list of source ports connected to this port on the same layer that can send data to * this port. This includes output ports that are connected on the outside to this port, and input * ports that are connected on the inside to this port. * * @param input TypedIOPort * @return A list of IOPort objects. */ private LinkedList _shallowSourcePortList(TypedIOPort input) { try { _workspace.getReadAccess(); Actor container = (Actor) input.getContainer(); Director excDirector = ((Actor) container).getExecutiveDirector(); int depthOfContainer = ((NamedObj) container).depthInHierarchy(); LinkedList result = new LinkedList(); Iterator ports = input.connectedPortList().iterator(); while (ports.hasNext()) { IOPort port = (IOPort) ports.next(); int depth = port.depthInHierarchy(); if (port.isInput() && (depth <= depthOfContainer)) { result.addLast(port); } else if (port.isOutput() && (depth == (depthOfContainer + 1))) { result.addLast(port); } } return result; } finally { _workspace.doneReading(); } }
public static boolean isBinaryTreeBST(BinaryTreeNode<Integer> tree) { LinkedList<QueueEntry> BFSQueue = new LinkedList<>(); BFSQueue.addLast(new QueueEntry(tree, Integer.MIN_VALUE, Integer.MAX_VALUE)); while (!BFSQueue.isEmpty()) { if (BFSQueue.getFirst().treeNode != null) { if (BFSQueue.getFirst().treeNode.getData() < BFSQueue.getFirst().lowerBound || BFSQueue.getFirst().treeNode.getData() > BFSQueue.getFirst().upperBound) { return false; } BFSQueue.addLast( new QueueEntry( BFSQueue.getFirst().treeNode.getLeft(), BFSQueue.getFirst().lowerBound, BFSQueue.getFirst().treeNode.getData())); BFSQueue.addLast( new QueueEntry( BFSQueue.getFirst().treeNode.getRight(), BFSQueue.getFirst().treeNode.getData(), BFSQueue.getFirst().upperBound)); } BFSQueue.removeFirst(); } return true; }
private void openExpression(QueryTranslatorImpl q, String lcToken) { nots.addLast(Boolean.FALSE); booleanTests.addLast(Boolean.FALSE); joins.addLast(new StringBuilder()); if (!"(".equals(lcToken)) { appendToken(q, "("); } }
public void enqueue(Animal a) { a.setOrder(order); order++; if (a instanceof Dog) { dogs.addLast((Dog) a); } else if (a instanceof Cat) { cats.addLast((Cat) a); } }
/* case_label = {constant} case minus? integer_constant | {default} default; */ public void outAConstantCaseLabel(AConstantCaseLabel node) { String s = (String) mProductions.removeLast(); int sign = 1; if (node.getMinus() != null) sign = -1; if (s.endsWith("L")) { mProductions.addLast(LongConstant.v(sign * Long.parseLong(s.substring(0, s.length() - 1)))); } else mProductions.addLast(IntConstant.v(sign * Integer.parseInt(s))); }
private void select() { out(); indent++; newline(); parenCounts.addLast(new Integer(parensSinceSelect)); afterByOrFromOrSelects.addLast(new Boolean(afterByOrSetOrFromOrSelect)); parensSinceSelect = 0; afterByOrSetOrFromOrSelect = true; }
@SuppressWarnings({"UnnecessaryBoxing"}) private void select() { out(); indent++; newline(); parenCounts.addLast(Integer.valueOf(parensSinceSelect)); afterByOrFromOrSelects.addLast(Boolean.valueOf(afterByOrSetOrFromOrSelect)); parensSinceSelect = 0; afterByOrSetOrFromOrSelect = true; }
public void addRule(String key, Rule rule) { if (hasRules(key)) { LinkedList ruleGroup = (LinkedList) rules.get(key); ruleGroup.addLast(rule); } else { LinkedList ruleGroup = new LinkedList(); ruleGroup.addLast(rule); rules.put(key, ruleGroup); } }
private Orderable parseMove(ParseContext pc, OrderPrefix op, final String[] tokens) throws OrderException { /* 3-StP: Army St Petersburg -> Moscow. (*bounce*) 1-Smy: Army Constantinople -> Aegean Sea -> Greece. keep parsing Locations until END or a -> is reached. so we keep looking for a -> until no more are found. if we have more than one, we'll add them to a list and then add that to the order Move order. */ LinkedList pathList = new LinkedList(); int idx = op.tokenIndex; int movTokIdx = findNextMoveToken(idx, tokens); while (movTokIdx != -1) { Location loc = parseLocation(pc, idx, movTokIdx, tokens); pathList.addLast(loc.getProvince()); idx = movTokIdx + 1; movTokIdx = findNextMoveToken(idx, tokens); } // add last location final Location loc = parseLocation(pc, idx, tokens.length, tokens); pathList.addLast(loc.getProvince()); // create Move order if (pathList.size() == 1) { if (pc.isRetreatPhase()) { return pc.orderFactory.createRetreat(op.power, op.location, op.unit, loc); } else { return pc.orderFactory.createMove(op.power, op.location, op.unit, loc); } } else if (pathList.size() > 1) { if (pc.isRetreatPhase()) { throw new OrderException("Convoyed Retreat orders are not allowed. Order: " + pc.orderText); } // add source location at beginning of move list pathList.addFirst(op.location.getProvince()); final Province[] route = (Province[]) pathList.toArray(new Province[pathList.size()]); return pc.orderFactory.createMove(op.power, op.location, op.unit, loc, route); } else { // this probably will not occur.... throw new OrderException("Invalid movement path in Move order: " + pc.orderText); } } // parseMove()
public String getLevelTraversal(EvaluationNode rootEvalNode, String correctTraversal) { LinkedList<EvaluationNode> nodeList = new LinkedList<EvaluationNode>(); String solution = ""; EvaluationNode currentNode = rootEvalNode; nodeList.addLast(currentNode); while (nodeList.size() != 0) { // solution.length()<correctTraversal.length() if (nodeList.size() != 0) { currentNode = nodeList.removeFirst(); solution += currentNode.node.getValue() + " "; if (currentNode != null) { if (currentNode.left != null) { nodeList.addLast(convertNodeToEvalNode(treeNodes, currentNode.left)); } if (currentNode.right != null) { nodeList.addLast(convertNodeToEvalNode(treeNodes, currentNode.right)); } } } else { solution += "."; } } if (solution.contains(".")) { errorMessage = "FeedBack: Your heap is incomplete, make sure that all valid " + "nodes are connected with edges."; } else if (!solution.equals(correctTraversal)) { String[] splitCorrect = correctTraversal.split(" "); String[] splitSolution = solution.split(" "); String correct = ""; boolean done = false; for (int i = 0; i < splitSolution.length; i++) { if (done == false) { if (splitCorrect[i] == splitSolution[i]) { correct += splitSolution[i] + " "; } else done = true; } } errorMessage = "Feedback: Incorrect MinHeap. The level traversal of your" + " MinHeap is correct through the segment: " + correct.trim() + " but the next visited node is incorrect."; if (splitSolution.length > splitCorrect.length) { // Make sure there are not to many nodes errorMessage = "Feedback: Incorrect MinHeap. Make sure you removed all of" + " the edges connected to the node specified to be removed."; } if (splitSolution[0] != splitCorrect[0]) { // Check to see if root is correct errorMessage = "Feedback: Incorrect Root Node. Remember, in a MinHeap the lowest" + " valued node should always be the root."; } } return solution.trim(); }
/** * 使用拓扑排序解决 * * @param numCourses * @param prerequisites * @return */ public boolean canFinish2(int numCourses, int[][] prerequisites) { if (prerequisites == null || prerequisites.length < 2) return true; Map<Integer, ArrayList<Integer>> graph = new HashMap<>(); int edgeLen = prerequisites.length; if (prerequisites[0].length != 2) return false; // 满足下面条件肯定有回路 if (edgeLen > (numCourses - 1) * numCourses / 2) return false; int[] degrees = new int[numCourses]; int a, b; ArrayList<Integer> list; for (int i = 0; i < edgeLen; i++) { a = prerequisites[i][0]; b = prerequisites[i][1]; degrees[b]++; // 认为没有重复的边 if (graph.containsKey(a)) { list = graph.get(a); } else { list = new ArrayList<Integer>(); } list.add(b); graph.put(a, list); } int countZero = 0; LinkedList<Integer> zerosDegree = new LinkedList<>(); for (int i = 0; i < numCourses; i++) { if (degrees[i] == 0) { zerosDegree.addLast(i); countZero++; } } if (zerosDegree.isEmpty()) return false; List<Integer> lst; while (!zerosDegree.isEmpty()) { int top = zerosDegree.getFirst(); zerosDegree.removeFirst(); lst = graph.get(top); if (lst != null) { for (int a1 : lst) { degrees[a1]--; if (degrees[a1] == 0) { zerosDegree.addLast(a1); countZero++; } } } } if (countZero == numCourses) return true; return false; }
public void outAIntegerConstant(AIntegerConstant node) { String s = (String) mProductions.removeLast(); StringBuffer buf = new StringBuffer(); if (node.getMinus() != null) buf.append('-'); buf.append(s); s = buf.toString(); if (s.endsWith("L")) { mProductions.addLast(LongConstant.v(Long.parseLong(s.substring(0, s.length() - 1)))); } else mProductions.addLast(IntConstant.v(Integer.parseInt(s))); }
/** * Execute and addThread with the given priority * * @param r * @param priority */ public void execute(Runnable r, Integer priority) { synchronized (mutex) { if (HIGH.equals(priority)) { highQueue.addLast(r); } else if (SINGLE.equals(priority)) { singleQueue.addLast(r); } else { lowQueue.addLast(r); } mutex.notifyAll(); } }
/** Enqueues the Runnable object, and executes it on a processor thread. */ public void dispatch(Runnable runner, boolean isLIFO) { isLIFO = false; synchronized (queue) { if (threadCount < maxThreadCount) { if (isLIFO) { queue.addFirst(runner); } else { queue.addLast(runner); } Thread processor = new Thread(this + " Processor") { public void run() { processEvents(); } }; threadCount++; // The processor thread must not be a daemon, // or else the Java VM might stop before // all runnables have been processed. try { processor.setDaemon(false); } catch (SecurityException e) { e.printStackTrace(); } try { processor.setPriority(priority); } catch (SecurityException e) { e.printStackTrace(); } processor.start(); return; } else if (blockingPolicy == ENQUEUE_WHEN_BLOCKED) { if (isLIFO) { queue.addFirst(runner); } else { queue.addLast(runner); } return; } } // implicit: if (threadCount >= maxThreadCount && blockingPolicy == RUN_WHEN_BLOCKED) runner.run(); }