public static void main(String[] args) {
    int n = 10000;
    if (args.length > 0) n = Integer.parseInt(args[0]);

    List<Integer> sorted = new ArrayList<Integer>(n);
    for (int i = 0; i < n; i++) sorted.add(new Integer(i));
    List<Integer> shuffled = new ArrayList<Integer>(sorted);
    Collections.shuffle(shuffled);

    Queue<Integer> pq = new PriorityQueue<Integer>(n, new MyComparator());
    for (Iterator<Integer> i = shuffled.iterator(); i.hasNext(); ) pq.add(i.next());

    List<Integer> recons = new ArrayList<Integer>();
    while (!pq.isEmpty()) recons.add(pq.remove());
    if (!recons.equals(sorted)) throw new RuntimeException("Sort test failed");

    recons.clear();
    pq = new PriorityQueue<Integer>(shuffled);
    while (!pq.isEmpty()) recons.add(pq.remove());
    if (!recons.equals(sorted)) throw new RuntimeException("Sort test failed");

    // Remove all odd elements from queue
    pq = new PriorityQueue<Integer>(shuffled);
    for (Iterator<Integer> i = pq.iterator(); i.hasNext(); )
      if ((i.next().intValue() & 1) == 1) i.remove();
    recons.clear();
    while (!pq.isEmpty()) recons.add(pq.remove());

    for (Iterator<Integer> i = sorted.iterator(); i.hasNext(); )
      if ((i.next().intValue() & 1) == 1) i.remove();

    if (!recons.equals(sorted)) throw new RuntimeException("Iterator remove test failed.");
  }
  /**
   * Returns date in the format: neededDatePattern, in case if year or month isn't entered, current
   * year/month is put.
   *
   * @return correct date.
   */
  private Date getCorrectedDate(String enteredDate) {
    Queue<String> dateParts = new ArrayDeque<>(3);
    StringBuilder number = new StringBuilder();
    for (char symbol : enteredDate.toCharArray()) {
      if (Character.isDigit(symbol)) {
        number.append(symbol);
      } else if (number.length() > 0) {
        dateParts.add(number.toString());
        number = new StringBuilder();
      }
    }
    if (number.length() > 0) {
      dateParts.add(number.toString());
    }

    Calendar currentDate = Calendar.getInstance();
    switch (dateParts.size()) {
      case 1:
        dateParts.add(Integer.toString(currentDate.get(Calendar.MONTH) + 1));
      case 2:
        dateParts.add(Integer.toString(currentDate.get(Calendar.YEAR)));
    }

    try {
      return new SimpleDateFormat("dd.MM.yyyy")
          .parse(dateParts.remove() + '.' + dateParts.remove() + '.' + dateParts.remove());

    } catch (ParseException e) {
      throw new RuntimeException(e); // todo change exception
    }
  }
    public void addItems(List<String> names, List<T> items) {
      if (!locationMap.isEmpty()) {
        throw new IllegalStateException("addItems can only be called once for any given Lattice");
      }
      Queue<String> nameQueue = new LinkedList<String>(names);
      Queue<T> itemQueue = new LinkedList<T>(items);
      for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
          for (int k = 0; k < size; k++) {
            if (nameQueue.isEmpty() || itemQueue.isEmpty()) return;
            String name = nameQueue.remove();
            T item = itemQueue.remove();
            locationMap.put(name, new PVector(i, j, k));
            contentsMap.put(name, item);
          }
        }
      }

      if (!nameQueue.isEmpty()) {
        log.warn(
            "Could not add all items to lattice of size "
                + size
                + ". Items remaining: "
                + nameQueue.size());
      }
    }
  /**
   * It is synchronized as it does merging of adjacent blocks. An easiest way to somewhat address
   * fragmentation problem.
   *
   * @param pointer2free
   */
  private void freeAndMerge(Pointer pointer2free) {
    synchronized (pointers) {
      pointers.remove(pointer2free);
      // merge adjacent blocks
      if (null != pointer2free.getPrev() && pointer2free.getPrev().isFree()) {
        // Merge previous
        pointers.remove(pointer2free.getPrev());
        pointer2free.setStart(pointer2free.getPrev().getStart());
        pointer2free.setPrev(pointer2free.getPrev().getPrev());
        // Recursive call
        freeAndMerge(pointer2free);
      }

      if (null != pointer2free.getNext() && pointer2free.getNext().isFree()) {
        // Merge Next
        pointers.remove(pointer2free.getNext());
        pointer2free.setEnd(pointer2free.getNext().getEnd());
        pointer2free.setNext(pointer2free.getNext().getNext());
        // Recursive call
        freeAndMerge(pointer2free);
      }
      if (!pointer2free.isFree()) {
        pointer2free.setFree(true);
        pointer2free.setClazz(null);
        pointers.add(pointer2free);
      }
    }
  }
Exemple #5
0
  public static void lightChange(Queue<Car> q) {
    // if light is true, that means the green light is for N and S
    // This means we must change the cars wait times in E and W
    Queue<Car> temp = new LinkedList<Car>();
    Car tc;
    while (!q.isEmpty()) {
      tc = q.remove();
      temp.add(tc);
    }
    int tnum = 1;
    q.clear();
    // System.out.println("In the light change");

    while (!temp.isEmpty()) {
      Car tcar = temp.remove();
      // System.out.println("Light Change: " + tcar.display());
      if (tnum == 1) {
        tcar.setTotalWait(3);
        tcar.setWaitTime(3);
        q.add(tcar);
      } else if (tnum == 2) {
        tcar.setTotalWait(2);
        tcar.setWaitTime(2);
        q.add(tcar);

      } else {

        tcar.setTotalWait(1);
        tcar.setWaitTime(1);
        q.add(tcar);
      }
      tnum++;
    }
  }
  // Algorithm to randomly shuffle the elements of a message.
  final Message shuffle(Message message) throws FormatException {

    Message shuffled = messages.make();

    // Read all elements of the packet and insert them in a Queue.
    Queue<String> old = new LinkedList<>();
    int N = 0;
    while (!message.isEmpty()) {
      old.add(message.readString());
      message = message.rest();
      N++;
    }

    // Then successively and randomly select which one will be inserted until none remain.
    for (int i = N; i > 0; i--) {
      // Get a random number between 0 and N - 1 inclusive.
      int n = crypto.getRandom(i - 1);

      for (int j = 0; j < n; j++) {
        old.add(old.remove());
      }

      // add the randomly selected element to the queue.
      shuffled = shuffled.attach(old.remove());
    }

    return shuffled;
  }
  /**
   * put the flip lake tile of the game
   *
   * @param players list of players
   */
  private void setUpLakeTile(Queue<Player> players) {
    Random r = new Random();
    int randomRedLantern = r.nextInt(players.size());
    Queue<Color> color = startLakeTile.getColorOfFourSides();
    // change the current player who get red lantern card
    color.add(color.remove());
    for (int i = 0; i < randomRedLantern; i++) {
      players.add(players.remove());
    }
    int current_number_player = 0;
    // add index to player
    for (int i = 0; i < players.size(); i++) {
      Player p = players.remove();
      p.setIndex(i);
      players.add(p);
    }

    for (Color lantern_color : color) {
      if (current_number_player == players.size()) {
        break;
      } else {
        current_number_player++;
      }
      Player p = players.remove();

      p.getLanternCards().add(supply.get(lantern_color).pop());
      players.add(p);
    }
  }
Exemple #8
0
 int[] nextPillBFS(Node start) {
   ArrayList<Node> alreadyVisited = new ArrayList<Node>();
   Queue<Node> nextToVisit = new LinkedList<Node>();
   Queue<Tuple> startDirection = new LinkedList<Tuple>();
   ArrayList<Edge> firstDirections = start.getEdges();
   for (int i = 0; i < firstDirections.size(); i++) {
     Node nextFieldToVisit = firstDirections.get(i).end;
     nextToVisit.add(nextFieldToVisit);
     startDirection.add(new Tuple(nextFieldToVisit.x - start.x, nextFieldToVisit.y - start.y));
   }
   Node lastTouched;
   Tuple beginningDirection;
   while (true) {
     if (nextToVisit.size() == 0) return new int[] {0, 0};
     lastTouched = nextToVisit.remove();
     beginningDirection = startDirection.remove();
     if (alreadyVisited.contains(lastTouched)) continue;
     if (lastTouched.hasPill()) {
       break;
     }
     alreadyVisited.add(lastTouched);
     ArrayList<Edge> neighbourEdges = lastTouched.getEdges();
     for (int i = 0; i < neighbourEdges.size(); i++) {
       nextToVisit.add(neighbourEdges.get(i).end);
       startDirection.add(beginningDirection);
     }
   }
   return new int[] {beginningDirection.x, beginningDirection.y};
 }
  /**
   * Run Method which simulates the number of threads running on the bridge
   *
   * @param None
   * @return None
   */
  public void run() {
    while (true) {
      Truck theTruck; // Stores the Truck Object

      // synchronized on truck queue before removing the truck objects
      synchronized (theTruckQueue) {
        // If there are no Trucks then wait for trucks to arrive
        while (theTruckQueue.isEmpty()) {
          try {
            theTruckQueue.wait();
          } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
        theTruck = theTruckQueue.remove();
      }
      // Check for the maximum trucks allowed on the bridge and max weight
      // allowed on the bridge
      // Do not allow any more trucks if we exceed any of the limit
      while (theBridgeQueue.size() == MAX_SIZE
          || (theTruck.getWeight() + getTotalWeight()) >= MAX_WEIGHT) {
        System.out.println("Total number of trucks on Bridge: " + theBridgeQueue.size());
        System.out.println("Total Weight on Bridge is: " + getTotalWeight());
        Truck truckOnBridge = theBridgeQueue.remove();
        System.out.println("The truck Entered " + truckOnBridge.getSide() + " of the Bridge left");
      }

      // Allow the trucks on the bridge on first come first serve basis
      System.out.println("Truck " + theTruck.getSide() + " is Entering the Bridge");
      theBridgeQueue.add(theTruck);
      System.out.println("Truck " + theTruck.getSide() + " is running on the Bridge");
    }
  }
  protected void sendStreamOfCommands(int[] sequenceNumbers, boolean expected, int expectedCount) {
    for (int i = 0; i < sequenceNumbers.length; i++) {
      int commandId = sequenceNumbers[i];

      ConsumerInfo info = new ConsumerInfo();
      info.setSelector("Cheese: " + commandId);
      info.setCommandId(commandId);

      transport.onCommand(info);
    }

    Queue<Object> exceptions = listener.getExceptions();
    Queue<Object> commands = listener.getCommands();
    if (expected) {
      if (!exceptions.isEmpty()) {
        Exception e = (Exception) exceptions.remove();
        e.printStackTrace();
        fail("Caught exception: " + e);
      }
      assertEquals("number of messages received", expectedCount, commands.size());

      assertEquals("Should have no buffered commands", 0, transport.getBufferedCommandCount());
    } else {
      assertTrue("Should have received an exception!", exceptions.size() > 0);
      Exception e = (Exception) exceptions.remove();
      LOG.info("Caught expected response: " + e);
    }
  }
Exemple #11
0
  private static int ladderLength(String start, String end, HashSet<String> dict) {
    int len = 0;

    Queue<String> wordQ = new LinkedList<String>();
    Queue<Integer> distQ = new LinkedList<Integer>();

    if (dict.size() == 0) return -1;

    wordQ.add(start);
    distQ.add(1);

    while (!wordQ.isEmpty()) {
      String currWord = wordQ.remove();
      Integer currDist = distQ.remove();

      if (currWord.equals(end)) return currDist;

      for (int i = 0; i < currWord.length(); i++) {
        char[] currArray = currWord.toCharArray();
        for (char c = 'a'; c <= 'z'; c++) {
          currArray[i] = c;
          String newStr = new String(currArray);
          if (dict.contains(newStr)) {
            wordQ.add(newStr);
            distQ.add(currDist + 1);
            dict.remove(newStr);
          }
        }
      }
    }

    return len;
  }
 private boolean setUpRemoteEngines(TestPlanEntity testPlan, Queue<Engine> engineQ) {
   List<EngineRole> engineRoles = testPlan.getTestTenant().getEngineList();
   Queue<EngineRole> engineRoleQ = new ArrayDeque<>();
   engineRoleQ.addAll(engineRoles);
   while (!engineRoleQ.isEmpty()) {
     EngineRole role = engineRoleQ.remove();
     if (engineQ.size() < engineRoles.size()) {
       _logger.error(
           String.format(
               "Testplan: %d can't init. Not enough available engines", testPlan.getId()));
       return true;
     }
     while (true) {
       Engine e = engineQ.remove();
       if (engineService.setRemoteEngineRole(e, role)) {
         break;
       }
       if (engineQ.isEmpty()) {
         _logger.error(
             String.format(
                 "Testplan: %d can't init. Not enough available engines", testPlan.getId()));
         return true;
       }
     }
   }
   return false;
 }
  // Returns a code tree that is optimal for these frequencies. Always contains at least 2 symbols,
  // to avoid degenerate trees.
  public CodeTree buildCodeTree() {
    // Note that if two nodes have the same frequency, then the tie is broken by which tree contains
    // the lowest symbol. Thus the algorithm is not dependent on how the queue breaks ties.
    Queue<NodeWithFrequency> pqueue = new PriorityQueue<NodeWithFrequency>();

    // Add leaves for symbols with non-zero frequency
    for (int i = 0; i < frequencies.length; i++) {
      if (frequencies[i] > 0) pqueue.add(new NodeWithFrequency(new Leaf(i), i, frequencies[i]));
    }

    // Pad with zero-frequency symbols until queue has at least 2 items
    for (int i = 0; i < frequencies.length && pqueue.size() < 2; i++) {
      if (i >= frequencies.length || frequencies[i] == 0)
        pqueue.add(new NodeWithFrequency(new Leaf(i), i, 0));
    }
    if (pqueue.size() < 2) throw new AssertionError();

    // Repeatedly tie together two nodes with the lowest frequency
    while (pqueue.size() > 1) {
      NodeWithFrequency nf1 = pqueue.remove();
      NodeWithFrequency nf2 = pqueue.remove();
      pqueue.add(
          new NodeWithFrequency(
              new InternalNode(nf1.node, nf2.node),
              Math.min(nf1.lowestSymbol, nf2.lowestSymbol),
              nf1.frequency + nf2.frequency));
    }

    // Return the remaining node
    return new CodeTree((InternalNode) pqueue.remove().node, frequencies.length);
  }
Exemple #14
0
  @SuppressWarnings("unchecked")
  private final Command mergeGetCommands(
      final Command currentCmd,
      final Queue writeQueue,
      final Queue<Command> executingCmds,
      CommandType expectedCommandType) {
    Map<Object, Command> mergeCommands = null;
    int mergeCount = 1;
    final CommandCollector commandCollector = creatCommandCollector();
    currentCmd.setStatus(OperationStatus.WRITING);

    commandCollector.visit(currentCmd);
    while (mergeCount < mergeFactor) {
      Command nextCmd = (Command) writeQueue.peek();
      if (nextCmd == null) {
        break;
      }
      if (nextCmd.isCancel()) {
        writeQueue.remove();
        continue;
      }
      if (nextCmd.getCommandType() == expectedCommandType) {
        if (mergeCommands == null) { // lazy initialize
          mergeCommands = new HashMap<Object, Command>(mergeFactor / 2);
          mergeCommands.put(currentCmd.getKey(), currentCmd);
        }
        if (log.isDebugEnabled()) {
          log.debug("Merge get command:" + nextCmd.toString());
        }
        nextCmd.setStatus(OperationStatus.WRITING);
        Command removedCommand = (Command) writeQueue.remove();
        // If the key is exists,add the command to associated list.
        if (mergeCommands.containsKey(removedCommand.getKey())) {
          final AssocCommandAware mergedGetCommand =
              (AssocCommandAware) mergeCommands.get(removedCommand.getKey());
          if (mergedGetCommand.getAssocCommands() == null) {
            mergedGetCommand.setAssocCommands(new ArrayList<Command>(5));
          }
          mergedGetCommand.getAssocCommands().add(removedCommand);
        } else {
          commandCollector.visit(nextCmd);
          mergeCommands.put(removedCommand.getKey(), removedCommand);
        }
        mergeCount++;
      } else {
        break;
      }
    }
    commandCollector.finish();
    if (mergeCount == 1) {
      return currentCmd;
    } else {
      if (log.isDebugEnabled()) {
        log.debug("Merge optimieze:merge " + mergeCount + " get commands");
      }
      return newMergedCommand(mergeCommands, mergeCount, commandCollector, expectedCommandType);
    }
  }
    @SuppressWarnings("synthetic-access")
    @Override
    public CurrencyLabelledMatrix1D buildObject(
        final FudgeDeserializer deserializer, final FudgeMsg message) {
      final FudgeMsg msg = message.getMessage(MATRIX_FIELD_NAME);

      final Queue<String> labelTypes = new LinkedList<String>();
      final Queue<FudgeField> labelValues = new LinkedList<FudgeField>();

      final List<Currency> keys = new LinkedList<Currency>();
      final List<Object> labels = new LinkedList<Object>();
      final List<Double> values = new LinkedList<Double>();

      for (final FudgeField field : msg) {
        switch (field.getOrdinal()) {
          case LABEL_TYPE_ORDINAL:
            labelTypes.add((String) field.getValue());
            break;
          case KEY_ORDINAL:
            keys.add(Currency.of((String) field.getValue()));
            break;
          case LABEL_ORDINAL:
            labelValues.add(field);
            break;
          case VALUE_ORDINAL:
            values.add((Double) field.getValue());
            break;
        }

        if (!labelTypes.isEmpty() && !labelValues.isEmpty()) {
          // Have a type and a value, which can be consumed
          final String labelType = labelTypes.remove();
          Class<?> labelClass;
          try {
            labelClass = LabelledMatrix1DBuilder.getLabelClass(labelType, _loadedClasses);
          } catch (final ClassNotFoundException ex) {
            throw new OpenGammaRuntimeException(
                "Could not deserialize label of type " + labelType, ex);
          }
          final FudgeField labelValue = labelValues.remove();
          final Object label = deserializer.fieldValueToObject(labelClass, labelValue);
          //          labels.add(Currency.of((String) label));
          labels.add(label);
        }
      }

      final int matrixSize = keys.size();
      final Currency[] keysArray = new Currency[matrixSize];
      keys.toArray(keysArray);
      final Object[] labelsArray = new Object[matrixSize];
      labels.toArray(labelsArray);
      final double[] valuesArray = Doubles.toArray(values);
      return new CurrencyLabelledMatrix1D(keysArray, labelsArray, valuesArray);
    }
  public void queueLinkedList() {
    Queue queue = new LinkedList();

    queue.add("One");
    queue.add("Two");
    queue.add("Three");

    System.out.println(queue.remove());
    System.out.println(queue.remove());
    System.out.println(queue.remove());
  }
Exemple #17
0
  void solve(Scanner in, PrintWriter out) {
    int n = in.nextInt();
    int k = in.nextInt();
    int m = in.nextInt();

    islands = new Island[n];
    for (int i = 0; i < n; i++) {
      islands[i] = new Island();
    }

    readEdges(in, k, false);
    readEdges(in, m, true);

    int bridgesUsed = 0;
    Queue<Island> bfs = new LinkedList<Island>();
    Queue<Island> candidates = new LinkedList<Island>();
    Island nextRoot = islands[0];
    while (nextRoot != null) {
      bfs.add(nextRoot);
      nextRoot = null;

      while (!bfs.isEmpty()) {
        Island land = bfs.remove();
        land.visited = true;

        for (Island other : land.tunnels) {
          if (!other.visited) {
            bfs.add(other);
          }
        }

        for (Island other : land.bridges) {
          if (!other.visited) {
            candidates.add(other);
          }
        }
      }

      while (!candidates.isEmpty()) {
        Island land = candidates.remove();
        if (!land.visited) {
          nextRoot = land;
          bridgesUsed++;
          break;
        }
      }
    }

    out.println(bridgesUsed);
  }
Exemple #18
0
  /** @param charFreq */
  static void caculateHuffManEncoding(CharFreq[] charFreq) {
    Queue<CharFreq> pQueue = new PriorityQueue<HuffmanCoding.CharFreq>();
    List<CharFreq> chF = Arrays.asList(charFreq);
    pQueue.addAll(chF);
    // Create Huffman tree
    while (pQueue.size() > 1) {
      CharFreq left = pQueue.remove();
      CharFreq right = pQueue.remove();
      CharFreq internal = new CharFreq(left.freq + right.freq, left, right);
      pQueue.add(internal);
    }

    // huffManEncoding(pQueue.remove(), new StringBuilder());
    huffManEncoding(pQueue.remove(), 0);
  }
  @Override
  public StreamObserver<StreamingRecognizeRequest> streamingRecognize(
      final StreamObserver<StreamingRecognizeResponse> responseObserver) {
    final Object response = responses.remove();
    StreamObserver<StreamingRecognizeRequest> requestObserver =
        new StreamObserver<StreamingRecognizeRequest>() {
          @Override
          public void onNext(StreamingRecognizeRequest value) {
            if (response instanceof StreamingRecognizeResponse) {
              responseObserver.onNext((StreamingRecognizeResponse) response);
            } else if (response instanceof Exception) {
              responseObserver.onError((Exception) response);
            } else {
              responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
            }
          }

          @Override
          public void onError(Throwable t) {
            responseObserver.onError(t);
          }

          @Override
          public void onCompleted() {
            responseObserver.onCompleted();
          }
        };
    return requestObserver;
  }
  @Override
  public String[] findFiles(final String folderName) {

    File folder = new File(folderName);
    if (!folder.exists()) {
      throw new IllegalArgumentException();
    }

    List<String> foundFiles = new ArrayList<String>();
    Queue<File> folders = new LinkedList<File>();

    folders.add(folder);

    while (!folders.isEmpty()) {

      File currentFolder = folders.remove();
      File[] currentFiles = currentFolder.listFiles();

      for (File f : currentFiles) {
        if (f.isDirectory()) {
          folders.add(f);
        } else if (f.isFile()) {
          foundFiles.add(f.getAbsolutePath());
        } else {
          throw new RuntimeException("It isn't file or folder");
        }
      }
    }

    return foundFiles.toArray(new String[foundFiles.size()]);
  }
Exemple #21
0
 /**
  * removes any tags from the validator's queue that match the given element
  *
  * @param element to remove from the queue
  */
 public void removeAll(String element) {
   for (HtmlTag h : tags) {
     if (h.toString().equals(element)) {
       tags.remove(h);
     }
   }
 }
Exemple #22
0
  private boolean existsUnblockedSemiDirectedPath(Node from, Node to, List<Node> cond, Graph G) {
    Queue<Node> Q = new LinkedList<Node>();
    Set<Node> V = new HashSet<Node>();
    Q.offer(from);
    V.add(from);

    while (!Q.isEmpty()) {
      Node t = Q.remove();
      if (t == to) return true;

      for (Node u : G.getAdjacentNodes(t)) {
        Edge edge = G.getEdge(t, u);
        Node c = Edges.traverseSemiDirected(t, edge);
        if (c == null) continue;
        if (cond.contains(c)) continue;
        if (c == to) return true;

        if (!V.contains(c)) {
          V.add(c);
          Q.offer(c);
        }
      }
    }

    return false;
  }
  /* Fill the bipartite graph if possible. */
  boolean[] solve() {
    Map<Integer, List<Integer>> gr = makeGraph();

    boolean[] truthTable = new boolean[count];
    // keep track of which ones we've visited
    boolean[] visited = new boolean[count];
    Queue<Integer> queue = new LinkedList<Integer>();
    truthTable[0] = true; // assume the first person tells the truth
    queue.add(0);

    // Breadth first search on graph
    while (!queue.isEmpty()) {
      int next = queue.remove();
      boolean truth = truthTable[next];
      List<Integer> list = gr.get(next);

      // Go through list and toggle when needed
      for (int i = 0; i < list.size(); i++) {
        int node = list.get(i);
        if (!visited[node]) {
          visited[node] = true;
          truthTable[node] = !truth;
          queue.add(node);
        }
      }
    }

    return truthTable;
  }
  /**
   * Locate each unexpanded Structure|Sequence and: 1. check that none of its fields is referenced
   * => do not expand 2. add all of its fields as leaves Note that #2 may end up adding additional
   * leaf structs &/or seqs
   */
  public void expand() {
    // Create a queue of unprocessed leaf compounds
    Queue<DapVariable> queue = new ArrayDeque<DapVariable>();

    for (int i = 0; i < variables.size(); i++) {
      DapVariable var = variables.get(i);
      if (!var.isTopLevel()) continue;
      // prime the queue
      if (var.getSort() == DapSort.STRUCTURE || var.getSort() == DapSort.SEQUENCE) {
        DapStructure struct = (DapStructure) var; // remember Sequence subclass Structure
        if (expansionCount(struct) == 0) queue.add(var);
      }
    }
    // Process the queue in prefix order
    while (queue.size() > 0) {
      DapVariable vvstruct = queue.remove();
      DapStructure dstruct = (DapStructure) vvstruct;
      for (DapVariable field : dstruct.getFields()) {
        if (findVariableIndex(field) < 0) {
          // Add field as leaf
          this.segments.add(new Segment(field));
          this.variables.add(field);
        }
        if (field.getSort() == DapSort.STRUCTURE || field.getSort() == DapSort.SEQUENCE) {
          if (expansionCount((DapStructure) field) == 0) queue.add(field);
        }
      }
    }
    this.expansion = Expand.EXPANDED;
  }
Exemple #25
0
 /** Sorts the index in the order of the date of publication of the posts. */
 protected void sortIndexes() {
   for (SingleIndex s : indexList) {
     for (int i = 0; i < postsPerIndex && !queue.isEmpty(); i++) {
       s.getPosts().add(queue.remove());
     }
   }
 }
Exemple #26
0
  /**
   * Using a serialized list of tree nodes to generate a binary tree. There is detail information:
   * https://leetcode.com/problems/binary-tree-inorder-traversal/
   *
   * @param serializedTreeNode a serialized list of tree nodes
   * @return the node of tree root
   */
  public static TreeNode generateTree(String serializedTreeNode) {
    String[] tokens = serializedTreeNode.split(",");
    if (tokens.length <= 0) return null;
    TreeNode root = new TreeNode(Integer.parseInt(tokens[0]));
    Queue<TreeNode> queue = new LinkedList<>();
    queue.add(root);
    int pos = 1;
    while (pos < tokens.length) {

      TreeNode temp = queue.remove();
      if (!tokens[pos].equals("#")) {
        TreeNode left = new TreeNode(Integer.parseInt(tokens[pos]));
        temp.left = left;
        queue.add(left);
      }
      pos++;

      if (pos >= tokens.length) break;
      if (!tokens[pos].equals("#")) {
        TreeNode right = new TreeNode(Integer.parseInt(tokens[pos]));
        temp.right = right;
        queue.add(right);
      }
      pos++;
    }
    return root;
  }
 /* Creates tree by mapping the array left to right, top to bottom. */
 public static TreeNode createTreeFromArray(int[] array) {
   if (array.length > 0) {
     TreeNode root = new TreeNode(array[0]);
     java.util.Queue<TreeNode> queue = new java.util.LinkedList<TreeNode>();
     queue.add(root);
     boolean done = false;
     int i = 1;
     while (!done) {
       TreeNode r = (TreeNode) queue.element();
       if (r.left == null) {
         r.left = new TreeNode(array[i]);
         i++;
         queue.add(r.left);
       } else if (r.right == null) {
         r.right = new TreeNode(array[i]);
         i++;
         queue.add(r.right);
       } else {
         queue.remove();
       }
       if (i == array.length) done = true;
     }
     return root;
   } else {
     return null;
   }
 }
Exemple #28
0
  // Reads: value | '[' value1, value2, valueN ']'
  private Object readValue(Queue<String> tokens) {
    String token = tokens.poll();
    if (!"[".equals(token)) {
      return token;

    } else {
      List<Object> values = new ArrayList<Object>();
      while (true) {
        if ("]".equals(tokens.peek())) {
          tokens.remove();
          break;
        }

        Object value = readValue(tokens);
        values.add(value);

        String delimiter = tokens.poll();
        if ("]".equals(delimiter)) {
          break;

        } else if (!",".equals(delimiter)) {
          throw new IllegalArgumentException(String.format("Expected a comma after [%s]!", value));
        }
      }

      return values;
    }
  }
 public void adjustTellerNumber() {
   // This is actually a control system. By adjusting
   // the numbers, you can reveal stability issues in
   // the control mechanism.
   // If line is too long, add another teller:
   if (customers.size() / workingTellers.size() > 2) {
     // If tellers are on break or doing
     // another job, bring one back:
     if (tellersDoingOtherThings.size() > 0) {
       Teller teller = tellersDoingOtherThings.remove();
       teller.serveCustomerLine();
       workingTellers.offer(teller);
       return;
     }
     // Else create (hire) a new teller
     Teller teller = new Teller(customers);
     exec.execute(teller);
     workingTellers.add(teller);
     return;
   }
   // If line is short enough, remove a teller:
   if (workingTellers.size() > 1 && customers.size() / workingTellers.size() < 2)
     reassignOneTeller();
   // If there is no line, we only need one teller:
   if (customers.size() == 0) while (workingTellers.size() > 1) reassignOneTeller();
 }
  @Override
  protected AbstractPlanNode recursivelyApply(AbstractPlanNode planNode) {
    assert (planNode != null);

    // breadth first:
    //     find AggregatePlanNode with exactly one child
    //     where that child is an AbstractScanPlanNode.
    //     Inline any qualifying AggregatePlanNode to its AbstractScanPlanNode.

    Queue<AbstractPlanNode> children = new LinkedList<AbstractPlanNode>();
    children.add(planNode);

    while (!children.isEmpty()) {
      AbstractPlanNode plan = children.remove();
      AbstractPlanNode newPlan = inlineAggregationApply(plan);
      if (newPlan != plan) {
        if (plan == planNode) {
          planNode = newPlan;
        } else {
          planNode.replaceChild(plan, newPlan);
        }
      }

      for (int i = 0; i < newPlan.getChildCount(); i++) {
        children.add(newPlan.getChild(i));
      }
    }

    return planNode;
  }