Java Code Examples for java.util.ArrayDeque#addLast()

The following examples show how to use java.util.ArrayDeque#addLast() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: j2objc   File: ArrayDequeTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * toArray() contains all elements in FIFO order
 */
public void testToArray() {
    ArrayDeque q = new ArrayDeque();
    for (int i = 0; i < SIZE; i++) {
        checkToArray(q);
        q.addLast(i);
    }
    // Provoke wraparound
    for (int i = 0; i < SIZE; i++) {
        checkToArray(q);
        assertEquals(i, q.poll());
        q.addLast(SIZE + i);
    }
    for (int i = 0; i < SIZE; i++) {
        checkToArray(q);
        assertEquals(SIZE + i, q.poll());
    }
}
 
Example 2
Source Project: es6draft   File: AsyncGeneratorObject.java    License: MIT License 6 votes vote down vote up
private PromiseObject enqueue(ExecutionContext cx, AsyncGeneratorRequest.CompletionType type, Object completion) {
    /* steps 1, 3 (not applicable) */
    /* step 2 */
    PromiseCapability<PromiseObject> promiseCapability = PromiseBuiltinCapability(cx);
    /* step 4 */
    ArrayDeque<AsyncGeneratorRequest> queue = this.queue;
    /* step 5 */
    AsyncGeneratorRequest request = new AsyncGeneratorRequest(type, completion, promiseCapability);
    /* step 6 */
    queue.addLast(request);
    /* step 7 */
    AsyncGeneratorState state = this.state;
    /* step 8 */
    if (!(state == AsyncGeneratorState.Executing || state == AsyncGeneratorState.SuspendedAwait)) {
        resumeNext(cx);
    }
    /* step 9 */
    return promiseCapability.getPromise();
}
 
Example 3
private void collectReferencedVirtualObjects(BlockT state, Set<VirtualObjectNode> virtual) {
    ArrayDeque<VirtualObjectNode> queue = new ArrayDeque<>(virtual);
    while (!queue.isEmpty()) {
        VirtualObjectNode object = queue.removeLast();
        int id = object.getObjectId();
        if (id != -1) {
            ObjectState objState = state.getObjectStateOptional(id);
            if (objState != null && objState.isVirtual()) {
                for (ValueNode entry : objState.getEntries()) {
                    if (entry instanceof VirtualObjectNode) {
                        VirtualObjectNode entryVirtual = (VirtualObjectNode) entry;
                        if (!virtual.contains(entryVirtual)) {
                            virtual.add(entryVirtual);
                            queue.addLast(entryVirtual);
                        }
                    }
                }
            }
        }
    }
}
 
Example 4
/**
 * addLast(x) succeeds
 */
public void testAddLast() {
    ArrayDeque q = new ArrayDeque();
    q.addLast(zero);
    q.addLast(one);
    assertSame(zero, q.peekFirst());
    assertSame(one, q.peekLast());
}
 
Example 5
Source Project: j2objc   File: ArrayDequeTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * addLast(x) succeeds
 */
public void testAddLast() {
    ArrayDeque q = new ArrayDeque();
    q.addLast(zero);
    q.addLast(one);
    assertSame(zero, q.peekFirst());
    assertSame(one, q.peekLast());
}
 
Example 6
Source Project: stateful-functions   File: MpscQueue.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Adds an element to this (unbound) queue.
 *
 * @param element the element to add.
 * @return the number of elements in the queue after the addition.
 */
public int add(T element) {
  Objects.requireNonNull(element);
  final Lock lock = this.lock;
  lock.lockUninterruptibly();
  try {
    ArrayDeque<T> active = this.active;
    active.addLast(element);
    return active.size();
  } finally {
    lock.unlock();
  }
}
 
Example 7
Source Project: flink-statefun   File: MpscQueue.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Adds an element to this (unbound) queue.
 *
 * @param element the element to add.
 * @return the number of elements in the queue after the addition.
 */
public int add(T element) {
  Objects.requireNonNull(element);
  final Lock lock = this.lock;
  lock.lockUninterruptibly();
  try {
    ArrayDeque<T> active = this.active;
    active.addLast(element);
    return active.size();
  } finally {
    lock.unlock();
  }
}
 
Example 8
Source Project: HackerRank-solutions   File: soln.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) {
    HashMap<Integer, Integer> map = new HashMap<>();
    ArrayDeque<Integer> deque     = new ArrayDeque<>();
    
    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();
    int m = scan.nextInt();
    int max = 0;
    
    for (int i = 0; i < n; i++) {
        /* Remove old value (if necessary) */
        if (i >= m) {
            int old = deque.removeFirst();
            if (map.get(old) == 1) {
                map.remove(old);
            } else {
                map.merge(old, -1, Integer::sum);
            }
        }
        
        /* Add new value */
        int num = scan.nextInt();
        deque.addLast(num);
        map.merge(num, 1, Integer::sum);
        
        max = Math.max(max, map.size());
        
        /* If all integers are unique, we have found our largest
           possible answer, so we can break out of loop */
        if (max == m) {
            break;
        }
    }
    
    scan.close();
    System.out.println(max);
}
 
Example 9
Source Project: YouTubeModdingTutorial   File: OreGenerator.java    License: MIT License 5 votes vote down vote up
@SubscribeEvent
public void handleChunkLoadEvent(ChunkDataEvent.Load event) {
    int dim = event.getWorld().provider.getDimension();

    boolean regen = false;
    NBTTagCompound tag = (NBTTagCompound) event.getData().getTag(RETRO_NAME);
    ChunkPos coord = event.getChunk().getPos();

    if (tag != null) {
        boolean generated = OregenConfig.RETROGEN && !tag.hasKey("generated");
        if (generated) {
            if (OregenConfig.VERBOSE) {
                MyMod.logger.log(Level.DEBUG, "Queuing Retrogen for chunk: " + coord.toString() + ".");
            }
            regen = true;
        }
    } else {
        regen = OregenConfig.RETROGEN;
    }

    if (regen) {
        ArrayDeque<ChunkPos> chunks = WorldTickHandler.chunksToGen.get(dim);

        if (chunks == null) {
            WorldTickHandler.chunksToGen.put(dim, new ArrayDeque<>(128));
            chunks = WorldTickHandler.chunksToGen.get(dim);
        }
        if (chunks != null) {
            chunks.addLast(coord);
            WorldTickHandler.chunksToGen.put(dim, chunks);
        }
    }
}
 
Example 10
Source Project: Android-Cheat-sheet   File: Dequeue.java    License: Apache License 2.0 5 votes vote down vote up
public static void findMaximumSlidingWindow(int[] arr,
                                            int windowSize) {
    if (arr.length < windowSize) return;

    ArrayDeque<Integer> list = new ArrayDeque();
    for (int i = 0; i < windowSize; i++) {

        while (!list.isEmpty() && arr[i] >= arr[list.peekLast()]) {
            list.removeLast();
        }
        list.addLast(i);
    }

    System.out.print(arr[list.peekFirst()] + " ");


    for (int i = windowSize; i < arr.length; i++) {

        while (!list.isEmpty() && arr[i] >= arr[list.peekLast()]) {
            list.removeLast();
        }

        if (!list.isEmpty() && list.peekFirst() <= i - windowSize) {
            list.removeFirst();
        }

        list.addLast(i);
        System.out.print(arr[list.peekFirst()] + " ");
    }
}
 
Example 11
private Tuple2<ExecutionGraph, Map<ExecutionAttemptID, Execution>> setupExecution(JobVertex v1, int dop1, JobVertex v2, int dop2) throws Exception {
	v1.setParallelism(dop1);
	v2.setParallelism(dop2);

	v1.setInvokableClass(BatchTask.class);
	v2.setInvokableClass(BatchTask.class);

	final ArrayDeque<CompletableFuture<LogicalSlot>> slotFutures = new ArrayDeque<>();
	for (int i = 0; i < dop1 + dop2; i++) {
		slotFutures.addLast(CompletableFuture.completedFuture(new TestingLogicalSlotBuilder().createTestingLogicalSlot()));
	}

	final SlotProvider slotProvider = new TestingSlotProvider(ignore -> slotFutures.removeFirst());

	DirectScheduledExecutorService executorService = new DirectScheduledExecutorService();

	// execution graph that executes actions synchronously
	ExecutionGraph eg = TestingExecutionGraphBuilder
		.newBuilder()
		.setFutureExecutor(executorService)
		.setSlotProvider(slotProvider)
		.setBlobWriter(blobWriter)
		.build();

	checkJobOffloaded(eg);

	eg.start(ComponentMainThreadExecutorServiceAdapter.forMainThread());

	List<JobVertex> ordered = Arrays.asList(v1, v2);
	eg.attachJobGraph(ordered);

	// schedule, this triggers mock deployment
	eg.scheduleForExecution();

	Map<ExecutionAttemptID, Execution> executions = eg.getRegisteredExecutions();
	assertEquals(dop1 + dop2, executions.size());

	return new Tuple2<>(eg, executions);
}
 
Example 12
/**
 * addLast(null) throws NPE
 */
public void testAddLastNull() {
    ArrayDeque q = new ArrayDeque();
    try {
        q.addLast(null);
        shouldThrow();
    } catch (NullPointerException success) {}
}
 
Example 13
/**
 * A recursive method for finding a complete mapping between blank nodes in model1 and blank nodes in model2. The
 * algorithm does a depth-first search trying to establish a mapping for each blank node occurring in model1.
 *
 * @param model1
 * @param model2
 * @return true if a complete mapping has been found, false otherwise.
 */
private static boolean matchModels(final List<? extends Statement> model1, final Model model2) {

	ArrayDeque<Iterator<Statement>> iterators = new ArrayDeque<>();
	ArrayDeque<Map<Resource, Resource>> bNodeMappings = new ArrayDeque<>();

	Map<Resource, Resource> bNodeMapping = Collections.emptyMap();
	int idx = 0;

	Iterator<Statement> iterator = null;
	while (true) {

		if (idx >= model1.size()) {
			return true;
		}

		Statement st1 = model1.get(idx);

		if (iterator == null) {

			List<Statement> matchingStats = findMatchingStatements(st1, model2, bNodeMapping);

			iterator = matchingStats.iterator();
		}

		if (iterator.hasNext()) {
			Statement st2 = iterator.next();

			// Map bNodes in st1 to bNodes in st2
			Map<Resource, Resource> newBNodeMapping = createNewBnodeMapping(bNodeMapping, st1, st2);

			iterators.addLast(iterator);
			bNodeMappings.addLast(bNodeMapping);

			iterator = null;

			bNodeMapping = newBNodeMapping;
			idx++;

		}

		if (iterator != null) {
			idx--;
			if (idx < 0) {
				return false;
			}
			iterator = iterators.removeLast();
			bNodeMapping = bNodeMappings.removeLast();
		}

	}

}
 
Example 14
Source Project: Any-Angle-Pathfinding   File: KeyToggler.java    License: The Unlicense 4 votes vote down vote up
private GridObjects peekSecondLast(ArrayDeque<GridObjects> list) {
    GridObjects top = list.removeLast();
    GridObjects peek = list.peekLast();
    list.addLast(top);
    return peek;
}
 
Example 15
private Tuple2<ExecutionGraph, Map<ExecutionAttemptID, Execution>> setupExecution(JobVertex v1, int dop1, JobVertex v2, int dop2) throws Exception {
	final JobID jobId = new JobID();

	v1.setParallelism(dop1);
	v2.setParallelism(dop2);

	v1.setInvokableClass(BatchTask.class);
	v2.setInvokableClass(BatchTask.class);

	final ArrayDeque<CompletableFuture<LogicalSlot>> slotFutures = new ArrayDeque<>();
	for (int i = 0; i < dop1 + dop2; i++) {
		slotFutures.addLast(CompletableFuture.completedFuture(new TestingLogicalSlot()));
	}

	final SlotProvider slotProvider = new TestingSlotProvider(ignore -> slotFutures.removeFirst());

	final JobInformation jobInformation = new DummyJobInformation(
		jobId,
		"some job");

	DirectScheduledExecutorService executorService = new DirectScheduledExecutorService();

	// execution graph that executes actions synchronously
	ExecutionGraph eg = new ExecutionGraph(
		jobInformation,
		executorService,
		TestingUtils.defaultExecutor(),
		AkkaUtils.getDefaultTimeout(),
		new NoRestartStrategy(),
		new RestartAllStrategy.Factory(),
		slotProvider,
		ExecutionGraph.class.getClassLoader(),
		blobWriter,
		AkkaUtils.getDefaultTimeout());
	checkJobOffloaded(eg);

	eg.start(TestingComponentMainThreadExecutorServiceAdapter.forMainThread());

	eg.setQueuedSchedulingAllowed(false);

	List<JobVertex> ordered = Arrays.asList(v1, v2);
	eg.attachJobGraph(ordered);

	// schedule, this triggers mock deployment
	eg.scheduleForExecution();

	Map<ExecutionAttemptID, Execution> executions = eg.getRegisteredExecutions();
	assertEquals(dop1 + dop2, executions.size());

	return new Tuple2<>(eg, executions);
}
 
Example 16
/**
 * Tests that a blocking batch job fails if there are not enough resources left to schedule the
 * succeeding tasks. This test case is related to [FLINK-4296] where finished producing tasks
 * swallow the fail exception when scheduling a consumer task.
 */
@Test
public void testNoResourceAvailableFailure() throws Exception {
	final JobID jobId = new JobID();
	JobVertex v1 = new JobVertex("source");
	JobVertex v2 = new JobVertex("sink");

	int dop1 = 1;
	int dop2 = 1;

	v1.setParallelism(dop1);
	v2.setParallelism(dop2);

	v1.setInvokableClass(BatchTask.class);
	v2.setInvokableClass(BatchTask.class);

	v2.connectNewDataSetAsInput(v1, DistributionPattern.POINTWISE, ResultPartitionType.BLOCKING);

	final ArrayDeque<CompletableFuture<LogicalSlot>> slotFutures = new ArrayDeque<>();
	for (int i = 0; i < dop1; i++) {
		slotFutures.addLast(CompletableFuture.completedFuture(new TestingLogicalSlotBuilder().createTestingLogicalSlot()));
	}

	final SlotProvider slotProvider = new TestingSlotProvider(ignore -> slotFutures.removeFirst());

	DirectScheduledExecutorService directExecutor = new DirectScheduledExecutorService();

	// execution graph that executes actions synchronously
	ExecutionGraph eg = createExecutionGraphWithoutQueuedScheduling(jobId, slotProvider, directExecutor, TestingUtils.defaultExecutor());

	eg.start(ComponentMainThreadExecutorServiceAdapter.forMainThread());

	checkJobOffloaded(eg);

	List<JobVertex> ordered = Arrays.asList(v1, v2);
	eg.attachJobGraph(ordered);

	// schedule, this triggers mock deployment
	eg.scheduleForExecution();

	ExecutionAttemptID attemptID = eg.getJobVertex(v1.getID()).getTaskVertices()[0].getCurrentExecutionAttempt().getAttemptId();
	eg.updateState(new TaskExecutionState(jobId, attemptID, ExecutionState.RUNNING));
	eg.updateState(new TaskExecutionState(jobId, attemptID, ExecutionState.FINISHED, null));

	assertEquals(JobStatus.FAILED, eg.getState());
}
 
Example 17
Source Project: flink   File: BufferStorageTestBase.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testSpillWhileReading() throws IOException {
	final int sequences = 10;

	final Random rnd = new Random();

	final int maxNumEventsAndBuffers = 300;
	final int maxNumChannels = 1656;

	ArrayDeque<ArrayDeque<BufferOrEvent>> expectedRolledSequences = new ArrayDeque<>();
	ArrayDeque<BufferOrEvent> expectedPendingSequence = new ArrayDeque<>();

	BufferStorage bufferStorage = createBufferStorage();

	// do multiple spilling / rolling over rounds
	for (int round = 0; round < 2 * sequences; round++) {

		if (round % 2 == 1) {
			// make this an empty sequence
			bufferStorage.rollOver();
			expectedRolledSequences.addFirst(expectedPendingSequence);
			expectedPendingSequence = new ArrayDeque<>();
		} else {
			// proper spilled sequence
			final long bufferSeed = rnd.nextLong();
			final Random bufferRnd = new Random(bufferSeed);

			final int numEventsAndBuffers = rnd.nextInt(maxNumEventsAndBuffers) + 1;
			final int numberOfChannels = rnd.nextInt(maxNumChannels) + 1;

			final ArrayList<BufferOrEvent> events = new ArrayList<>(128);

			int generated = 0;
			while (generated < numEventsAndBuffers) {

				if (rnd.nextDouble() < 0.5) {
					// add a new record
					boolean isEvent = rnd.nextDouble() < 0.05;
					BufferOrEvent evt;
					if (isEvent) {
						evt = generateRandomEvent(rnd, numberOfChannels);
						events.add(evt);
					} else {
						evt = generateRandomBuffer(bufferRnd.nextInt(PAGE_SIZE) + 1, bufferRnd.nextInt(numberOfChannels));
					}
					bufferStorage.add(evt);

					expectedPendingSequence.addLast(evt);
					generated++;
				} else {
					// consume a record
					bufferStorage.rollOver();
					expectedRolledSequences.addFirst(expectedPendingSequence);
					expectedPendingSequence = new ArrayDeque<>();

					assertNextBufferOrEvent(expectedRolledSequences, bufferStorage);
				}
			}
			bufferStorage.rollOver();
			expectedRolledSequences.addFirst(expectedPendingSequence);
			expectedPendingSequence = new ArrayDeque<>();
		}
	}

	// consume all the remainder
	while (!expectedRolledSequences.isEmpty()) {
		assertNextBufferOrEvent(expectedRolledSequences, bufferStorage);
	}
}
 
Example 18
Source Project: litho   File: DataFlowGraph.java    License: Apache License 2.0 4 votes vote down vote up
@GuardedBy("this")
private void regenerateSortedNodes() {
  mSortedNodes.clear();

  if (mBindings.size() == 0) {
    return;
  }

  final ArraySet<ValueNode> leafNodes = new ArraySet<>();
  final SimpleArrayMap<ValueNode, Integer> nodesToOutputsLeft = new SimpleArrayMap<>();

  for (int i = 0, bindingsSize = mBindings.size(); i < bindingsSize; i++) {
    final ArrayList<ValueNode> nodes = mBindings.get(i).getAllNodes();
    for (int j = 0, nodesSize = nodes.size(); j < nodesSize; j++) {
      final ValueNode node = nodes.get(j);
      final int outputCount = node.getOutputCount();
      if (outputCount == 0) {
        leafNodes.add(node);
      } else {
        nodesToOutputsLeft.put(node, outputCount);
      }
    }
  }

  if (!nodesToOutputsLeft.isEmpty() && leafNodes.isEmpty()) {
    throw new DetectedCycleException(
        "Graph has nodes, but they represent a cycle with no leaf nodes!");
  }

  final ArrayDeque<ValueNode> nodesToProcess = new ArrayDeque<>();
  nodesToProcess.addAll(leafNodes);

  while (!nodesToProcess.isEmpty()) {
    final ValueNode next = nodesToProcess.pollFirst();
    mSortedNodes.add(next);
    NodeState nodeState = mNodeStates.get(next);
    if (nodeState == null) {
      String message =
          next.getClass().getSimpleName() + " : InputNames " + next.buildDebugInputsString();
      // Added for debugging T67342661
      ComponentsReporter.emitMessage(
          ComponentsReporter.LogLevel.ERROR, STATE_NOT_INTIALIZED_FOR_VALUE_NODE, message);
    }
    for (ValueNode input : next.getAllInputs()) {
      final int outputsLeft = nodesToOutputsLeft.get(input) - 1;
      nodesToOutputsLeft.put(input, outputsLeft);
      if (outputsLeft == 0) {
        nodesToProcess.addLast(input);
      } else if (outputsLeft < 0) {
        throw new DetectedCycleException("Detected cycle.");
      }
    }
  }

  int expectedTotalNodes = nodesToOutputsLeft.size() + leafNodes.size();
  if (mSortedNodes.size() != expectedTotalNodes) {
    throw new DetectedCycleException(
        "Had unreachable nodes in graph -- this likely means there was a cycle");
  }

  Collections.reverse(mSortedNodes);
  mIsDirty = false;
}
 
Example 19
void run() throws Throwable {
//         System.out.printf(
//             "iterations=%d size=%d, warmup=%1g, filter=\"%s\"%n",
//             iterations, size, warmupSeconds, filter);

        final ArrayList<Integer> al = new ArrayList<>(size);

        // Populate collections with random data
        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
        for (int i = 0; i < size; i++)
            al.add(rnd.nextInt(size));

        final ArrayDeque<Integer> ad = new ArrayDeque<>(al);
        final ArrayBlockingQueue<Integer> abq = new ArrayBlockingQueue<>(al.size());
        abq.addAll(al);

        // shuffle circular array elements so they wrap
        for (int i = 0, n = rnd.nextInt(size); i < n; i++) {
            ad.addLast(ad.removeFirst());
            abq.add(abq.remove());
        }

        ArrayList<Job> jobs = new ArrayList<>(Arrays.asList());

        List.of(al, ad, abq,
                new LinkedList<>(al),
                new PriorityQueue<>(al),
                new Vector<>(al),
                new ConcurrentLinkedQueue<>(al),
                new ConcurrentLinkedDeque<>(al),
                new LinkedBlockingQueue<>(al),
                new LinkedBlockingDeque<>(al),
                new LinkedTransferQueue<>(al),
                new PriorityBlockingQueue<>(al))
            .stream()
            .forEach(x -> {
                         jobs.addAll(collectionJobs(x));
                         if (x instanceof Deque)
                             jobs.addAll(dequeJobs((Deque<Integer>)x));
                     });

        if (reverse) Collections.reverse(jobs);
        if (shuffle) Collections.shuffle(jobs);

        time(filter(filter, jobs));
    }
 
Example 20
/**
 * Returns a new deque of given size containing consecutive
 * Integers 0 ... n - 1.
 */
private static ArrayDeque<Integer> populatedDeque(int n) {
    // Randomize various aspects of memory layout, including
    // capacity slop and wraparound.
    final ArrayDeque<Integer> q;
    ThreadLocalRandom rnd = ThreadLocalRandom.current();
    switch (rnd.nextInt(6)) {
    case 0: q = new ArrayDeque<Integer>();      break;
    case 1: q = new ArrayDeque<Integer>(0);     break;
    case 2: q = new ArrayDeque<Integer>(1);     break;
    case 3: q = new ArrayDeque<Integer>(Math.max(0, n - 1)); break;
    case 4: q = new ArrayDeque<Integer>(n);     break;
    case 5: q = new ArrayDeque<Integer>(n + 1); break;
    default: throw new AssertionError();
    }
    switch (rnd.nextInt(3)) {
    case 0:
        q.addFirst(42);
        assertEquals((Integer) 42, q.removeLast());
        break;
    case 1:
        q.addLast(42);
        assertEquals((Integer) 42, q.removeFirst());
        break;
    case 2: /* do nothing */ break;
    default: throw new AssertionError();
    }
    assertTrue(q.isEmpty());
    if (rnd.nextBoolean())
        for (int i = 0; i < n; i++)
            assertTrue(q.offerLast((Integer) i));
    else
        for (int i = n; --i >= 0; )
            q.addFirst((Integer) i);
    assertEquals(n, q.size());
    if (n > 0) {
        assertFalse(q.isEmpty());
        assertEquals((Integer) 0, q.peekFirst());
        assertEquals((Integer) (n - 1), q.peekLast());
    }
    return q;
}