// Adds a number into the data structure.
 public void addNum(int num) {
   minheap.offer(num);
   maxheap.offer(minheap.poll());
   if (maxheap.size() > minheap.size()) {
     minheap.offer(maxheap.poll());
   }
 }
Exemplo n.º 2
0
 // Adds a number into the data structure.
 public void addNum(int num) {
   max.offer(num);
   min.offer(max.poll());
   if (max.size() < min.size()) {
     max.offer(min.poll());
   }
 }
Exemplo n.º 3
0
 public ListNode mergeKLists(ArrayList<ListNode> lists) {
   if (lists == null || lists.isEmpty()) return null;
   PriorityQueue<ListNode> heap =
       new PriorityQueue<ListNode>(
           lists.size(),
           new Comparator<ListNode>() {
             public int compare(ListNode o1, ListNode o2) {
               return o1.data > o2.data ? 1 : (o1.data < o2.data ? -1 : 0);
             }
           });
   for (ListNode node : lists) {
     if (node != null) {
       heap.add(node);
     }
   }
   ListNode head = null, cur = null;
   while (!heap.isEmpty()) {
     if (head == null) {
       head = heap.poll();
       cur = head;
     } else {
       cur.next = heap.poll();
       cur = cur.next;
     }
     if (cur.next != null) {
       heap.add(cur.next);
     }
   }
   return head;
 }
Exemplo n.º 4
0
  public int[] firstK(int arr[], int k) {
    int[] arrK = new int[k];
    // max heap
    PriorityQueue<Integer> heap =
        new PriorityQueue<Integer>(
            k,
            new Comparator<Integer>() {

              @Override
              public int compare(Integer arg0, Integer arg1) {
                return -arg0.compareTo(arg1);
              }
            });

    for (int i = 0; i < arr.length; ++i) {
      heap.add(arr[i]);
      if (heap.size() > k) {
        heap.poll();
      }
    }
    int idx = 0;
    while (!heap.isEmpty()) {
      arrK[idx++] = heap.poll();
    }
    return arrK;
  }
Exemplo n.º 5
0
 /** This methods extracts and stores all open right branches for future exploration */
 protected void extractOpenRightBranches(SearchLoop searchLoop) {
   // update parameters for restarts
   if (nodesRecompute > 0) {
     double ratio = nodesRecompute * 1.d / searchLoop.mMeasures.getNodeCount();
     if (ratio > b && Z <= N) {
       Z *= 2;
     } else if (ratio < a && Z >= 2) {
       Z /= 2;
     }
   }
   limit += Z;
   // then start the extraction of open right branches
   int i = compareSubpath(searchLoop);
   if (i < _unkopen.size()) {
     extractOB(searchLoop, i);
   }
   // finally, get the best ORB to keep up the search
   Open next = opens.poll();
   while (next != null && !isValid(next.currentBound())) {
     next = opens.poll();
   }
   if (next != null) {
     copen = next.toArray();
     // the decision in 0 is the last taken, then the array us reversed
     ArrayUtils.reverse(copen);
     current = 0;
     nodesRecompute = searchLoop.mMeasures.getNodeCount() + copen.length;
   } else {
     // to be sure not to use the previous path
     current = copen.length;
   }
   // then do the restart
   searchLoop.restart();
 }
  protected List<InputSplit> combineSplits(
      PriorityQueue<LuceneIndexInputSplit> splits,
      long maxCombinedIndexSizePerSplit,
      long maxNumIndexesPerSplit) {

    // now take the one-split-per-index splits and combine them into multi-index-per-split splits
    List<InputSplit> combinedSplits = Lists.newLinkedList();
    LuceneIndexInputSplit currentSplit = splits.poll();
    while (currentSplit != null) {
      while (currentSplit.getLength() < maxCombinedIndexSizePerSplit) {
        LuceneIndexInputSplit nextSplit = splits.peek();
        if (nextSplit == null) {
          break;
        }
        if (currentSplit.getLength() + nextSplit.getLength() > maxCombinedIndexSizePerSplit) {
          break;
        }
        if (currentSplit.getIndexDirs().size() >= maxNumIndexesPerSplit) {
          break;
        }
        currentSplit.combine(nextSplit);
        splits.poll();
      }
      combinedSplits.add(currentSplit);
      currentSplit = splits.poll();
    }
    return combinedSplits;
  }
Exemplo n.º 7
0
    /**
     * Advance the iterator. Should only be called if {@link #isValid()} returned true. Valid can
     * only chance after calls to {@link #next()}.
     */
    public void next() {
      newKeyGroup = false;
      newKVState = false;

      final RocksIterator rocksIterator = currentSubIterator.getIterator();
      rocksIterator.next();

      byte[] oldKey = currentSubIterator.getCurrentKey();
      if (rocksIterator.isValid()) {
        currentSubIterator.currentKey = rocksIterator.key();

        if (isDifferentKeyGroup(oldKey, currentSubIterator.getCurrentKey())) {
          heap.offer(currentSubIterator);
          currentSubIterator = heap.poll();
          newKVState = currentSubIterator.getIterator() != rocksIterator;
          detectNewKeyGroup(oldKey);
        }
      } else {
        rocksIterator.close();

        if (heap.isEmpty()) {
          currentSubIterator = null;
          valid = false;
        } else {
          currentSubIterator = heap.poll();
          newKVState = true;
          detectNewKeyGroup(oldKey);
        }
      }
    }
Exemplo n.º 8
0
  @Override
  public synchronized List<T> getTopK() {
    Comparator<T> comparator =
        new Comparator<T>() {
          public int compare(T key1, T key2) {
            return Longs.compare(counts.get(key1), counts.get(key2));
          }
        };
    PriorityQueue<T> topK = new PriorityQueue<T>(k, comparator);

    for (Map.Entry<T, Long> entry : counts.entrySet()) {
      if (topK.size() < k) {
        topK.offer(entry.getKey());
      } else if (entry.getValue() > counts.get(topK.peek())) {
        topK.offer(entry.getKey());
        topK.poll();
      }
    }

    LinkedList<T> sortedTopK = new LinkedList<T>();

    while (!topK.isEmpty()) {
      sortedTopK.addFirst(topK.poll());
    }

    return sortedTopK;
  }
  /**
   * Get top N elements
   *
   * @param vec the vec to extract the top elements from
   * @param N the number of elements to extract
   * @return the indices and the sorted top N elements
   */
  private static List<Double> getTopN(INDArray vec, int N) {
    ArrayComparator comparator = new ArrayComparator();
    PriorityQueue<Double[]> queue = new PriorityQueue<>(vec.rows(), comparator);

    for (int j = 0; j < vec.length(); j++) {
      final Double[] pair = new Double[] {vec.getDouble(j), (double) j};
      if (queue.size() < N) {
        queue.add(pair);
      } else {
        Double[] head = queue.peek();
        if (comparator.compare(pair, head) > 0) {
          queue.poll();
          queue.add(pair);
        }
      }
    }

    List<Double> lowToHighSimLst = new ArrayList<>();

    while (!queue.isEmpty()) {
      double ind = queue.poll()[1];
      lowToHighSimLst.add(ind);
    }
    return Lists.reverse(lowToHighSimLst);
  }
Exemplo n.º 10
0
  public static void main(String args[]) throws IOException {

    String text = "C:\\Users\\Roshan Rajan\\Desktop\\squaredance.txt";
    String gender = "";
    PriorityQueue<String> men = new PriorityQueue<String>();
    PriorityQueue<String> women = new PriorityQueue<String>();
    BufferedReader input = new BufferedReader(new FileReader(text));
    String line = null;
    while ((line = input.readLine()) != null) {
      gender = line.substring(0, 1);
      if (gender.equals("M")) men.add(line.substring(2));
      else women.add(line.substring(2));
    }
    input.close();

    while (!men.isEmpty() && !women.isEmpty()) {
      System.out.println("The couples are ");
      System.out.println(men.poll() + " is Dancing with " + women.poll());
    }
    if (men.isEmpty()) {
      System.out.println(women.size() + " girls are Waiting to Dance");
      System.out.println(women.peek() + " is the first one waiting");
    }
    if (women.isEmpty()) {
      System.out.println(men.size() + " guys are Waiting to Dance");
      System.out.println(men.peek() + " is the first one waiting");
    }
  }
Exemplo n.º 11
0
  private HeightEvent nextEvent() {
    EdgeCollision ec;

    for (; ; ) {
      ec = faceEvents.poll();
      if (ec == null) break;
      // valid if we haven't seen it, and it's height is "greater" than
      // the current skeleton height
      if (!skel.seen.contains(ec) && ec.loc.z - skel.height > -0.001) break;
    }

    HeightEvent he = miscEvents.peek();

    if (ec == null) {
      return miscEvents.poll(); // might be null!
    }
    if (he == null) {
      skel.seen.add(ec);
      return ec; // might be null!
    }

    if (he.getHeight() <= ec.getHeight()) {
      faceEvents.add(ec);
      return miscEvents.poll(); // return he
    } else {
      skel.seen.add(ec);
      return ec; // return ec
    }
  }
Exemplo n.º 12
0
  @Override
  void solve(Set<? extends Job> jobs) {
    Job[] sortedJobs = jobs.toArray(new Job[jobs.size()]);
    Arrays.sort(sortedJobs, Job::compareArrivalTime);

    processTime = totWT = 0;
    long usefulTime = 0;
    int jobCount = jobs.size();
    PriorityQueue<Job> queue = new PriorityQueue<>(Job::compareBurstTime);
    for (Job job : sortedJobs) {
      if (job == null) {
        jobCount--;
        continue;
      }

      while (!queue.isEmpty() && processTime < job.getArrivalTime()) {
        Job nextJob = queue.poll();
        long arrivalTime = nextJob.getArrivalTime();
        long burstTime = nextJob.getBurstTime();

        if (processTime < nextJob.getArrivalTime()) {
          processList.add(new RunningProcess("Idle", arrivalTime - processTime));
          processTime = arrivalTime;
        }

        processList.add(new RunningProcess("P" + nextJob.getId(), burstTime));
        usefulTime += burstTime;
        totWT += processTime - arrivalTime;
        processTime += burstTime;
      }

      queue.add(job);
    }

    while (!queue.isEmpty()) {
      Job nextJob = queue.poll();
      long arrivalTime = nextJob.getArrivalTime();
      long burstTime = nextJob.getBurstTime();

      if (processTime < nextJob.getArrivalTime()) {
        processList.add(new RunningProcess("Idle", arrivalTime - processTime));
        processTime = arrivalTime;
      }

      processList.add(new RunningProcess("P" + nextJob.getId(), burstTime));
      usefulTime += burstTime;
      totWT += processTime - arrivalTime;
      processTime += burstTime;
    }

    totRT = totWT;
    totTAT = totWT + usefulTime;

    avgRT = avgWT = (double) totWT / (double) jobCount;
    avgTAT = (double) totTAT / (double) jobCount;

    utilization = usefulTime * 100.0 / processTime;
  }
Exemplo n.º 13
0
 public Integer removeMedian() {
   if (min.size() > max.size()) {
     return max.poll();
   } else if (min.size() > max.size()) {
     return min.poll();
   } else {
     return ((max.poll() + min.poll()) / 2);
   }
 }
Exemplo n.º 14
0
  public static void main(String[] args) {
    // Convert het woord naar chars
    String woord = "bananen";
    ArrayList<Character> chars = new ArrayList<>();
    ArrayList<HuffKnoop> knopen = new ArrayList<>();
    for (int i = 0; i < woord.length(); i++) {
      chars.add(woord.charAt(i));
    }

    // 1. Frequentie van tekens
    Set<Character> uniqueChars = new HashSet<>(chars);
    for (char c : uniqueChars) {
      knopen.add(new HuffKnoop(c, Collections.frequency(chars, c), null, null));
    }

    // 2. Sorteer de tekens op frequentie
    PriorityQueue queue =
        new PriorityQueue(
            uniqueChars.size(),
            new Comparator<HuffKnoop>() {
              @Override
              public int compare(HuffKnoop o1, HuffKnoop o2) {
                return o1.frequentie - o2.frequentie;
              }
            });

    for (HuffKnoop knoop : knopen) {
      queue.add(knoop);
    }

    // 3. Maken van de huffman boom.
    while (queue.size() > 1) {
      HuffKnoop knoopLinks = (HuffKnoop) queue.poll();
      HuffKnoop knoopRechts = (HuffKnoop) queue.poll();
      queue.add(
          new HuffKnoop(
              '\0', knoopLinks.frequentie + knoopRechts.frequentie, knoopLinks, knoopRechts));
    }

    // 4. Aflezen van de codes
    boom = (HuffKnoop) queue.poll();
    generateCodes(boom, "");

    Iterator it = codes.entrySet().iterator();
    while (it.hasNext()) {
      Map.Entry pair = (Map.Entry) it.next();
      System.out.println(pair.getKey() + " " + pair.getValue());
    }

    // 5. Coderen
    String encodedMessage = encodeMessage(woord);
    System.out.println(encodedMessage);

    // 6. Decoderen
    String decodedMessage = decodeMessage(encodedMessage);
    System.out.println(decodedMessage);
  }
Exemplo n.º 15
0
 @Test
 public void test1p() {
   PriorityQueue<Integer> queue = new PriorityQueue<>(4);
   queue.add(1);
   queue.add(2);
   queue.add(3);
   queue.add(4);
   Assert.assertEquals(Integer.valueOf(1), queue.poll());
   Assert.assertFalse(queue.poll().equals(4));
 }
Exemplo n.º 16
0
  private void makeAFreeSpace() {

    while ((activeCache.size() + passiveCache.size()) >= CACHE_SIZE && !passiveCache.isEmpty()) {
      passiveCache.poll().getRenderedBitmap().recycle();
    }

    while ((activeCache.size() + passiveCache.size()) >= CACHE_SIZE && !activeCache.isEmpty()) {
      activeCache.poll().getRenderedBitmap().recycle();
    }
  }
Exemplo n.º 17
0
  public Node huffman(PriorityQueue<Node> lst) {
    int n = lst.size();
    for (int i = 1; i < n; i++) {
      Node x = lst.poll();
      Node y = lst.poll();

      Node z = new Node(x.freq + y.freq, x, y);
      lst.add(z);
    }
    return lst.poll();
  }
Exemplo n.º 18
0
  public PPath getShortestPath() {
    PPath start = new PPath(null, src.x, src.y, getEstimatedDist(src.x, src.y));
    pQueue.add(start);
    PPath cur = pQueue.poll();
    while (cur.value.x != dest.x || cur.value.y != dest.y) {
      List<PPath> nextPaths = getNext(cur);
      for (PPath nextPath : nextPaths) {
        pQueue.add(nextPath);
      }
      cur = pQueue.poll();
    }

    return cur;
  }
Exemplo n.º 19
0
  public static boolean canPartitionKarmarkarKarp(int[] baseArr) {
    // create max heap
    PriorityQueue<Integer> heap = new PriorityQueue<Integer>(baseArr.length, REVERSE_INT_CMP);
    for (int value : baseArr) {
      heap.add(value);
    }
    while (heap.size() > 1) {
      int val1 = heap.poll();
      int val2 = heap.poll();

      heap.add(val1 - val2);
    }
    return heap.poll() == 0;
  }
Exemplo n.º 20
0
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int row = sc.nextInt();
    int column = sc.nextInt();

    char[][] cityMap = new char[row][column]; // 获取城市的地图
    for (int i = 0; i < row; i++) {
      String str = sc.next();
      for (int j = 0; j < column; j++) {
        cityMap[i][j] = str.charAt(j);
      }
    }

    // 获取可能的四种3*3的hi的布局
    char[][] hi1 = new char[3][3];
    char[][] hi2 = new char[3][3];
    char[][] hi3 = new char[3][3];
    char[][] hi4 = new char[3][3];

    for (int i = 0; i < 3; i++) {
      String str = sc.next();
      for (int j = 0; j < 3; j++) {
        char c = str.charAt(j);
        hi1[i][j] = c;
        hi2[2 - i][2 - j] = c;
        hi3[2 - j][i] = c;
        hi4[j][2 - i] = c;
      }
    }

    PriorityQueue<Point> queen = new PriorityQueue<>();

    for (int i = 1; i < row - 1; i++) {
      for (int j = 1; j < column - 1; j++) {
        if (isHere(hi1, cityMap, i, j)
            || isHere(hi2, cityMap, i, j)
            || isHere(hi3, cityMap, i, j)
            || isHere(hi4, cityMap, i, j)) {
          queen.add(new Point(i, j));
        }
      }
    }

    Point p = queen.poll();

    while (p != null) {
      System.out.println((p.x + 1) + " " + (p.y + 1));
      p = queen.poll();
    }
  }
  public static void main(String[] args) {
    PriorityQueue<Student> studenten = new PriorityQueue();

    Student s1 = new Student(1, DateUtil.getDateInstance(1978, 3, 18));
    Student s2 = new Student(2, DateUtil.getDateInstance(1962, 1, 24));
    Student s3 = new Student(3, DateUtil.getDateInstance(1978, 5, 31));

    studenten.add(s1);
    studenten.add(s2);
    studenten.add(s3);

    System.out.println(studenten.poll().getGeboorteDatum());
    System.out.println(studenten.poll().getGeboorteDatum());
    System.out.println(studenten.poll().getGeboorteDatum());
  }
 protected TreeNode HuffTree(int[] count) {
   PriorityQueue<TreeNode> q = new PriorityQueue<TreeNode>();
   for (int i = 0; i < count.length; i++) {
     if (count[i] > 0) {
       q.add(new TreeNode(i, count[i]));
     }
   }
   q.add(new TreeNode(PSEUDO_EOF, 1));
   while (q.size() > 1) {
     TreeNode a = q.poll();
     TreeNode b = q.poll();
     q.add(new TreeNode(-1, a.myWeight + b.myWeight, a, b));
   }
   return q.poll();
 }
Exemplo n.º 23
0
  /** Implementation of dijkstra's algorithm using a binary heap. */
  private void dijkstra(final PriorityQueue<Vertex> q) {
    Vertex u, v;
    while (!q.isEmpty()) {

      u = q.poll(); // vertex with shortest distance (first iteration
      // will return source)
      // System.out.println("id is"+u.getId());
      // System.out.println(u.getDist());
      // System.out.println(u.getNeighborV().size());
      // System.out.println(this.endNodeId)
      if (u.getDist() == Double.MAX_VALUE)
        break; // we can ignore u (and any other remaining vertices)
      // since they are unreachable

      // look at distances to each neighbor
      for (Map.Entry<Vertex, Double> a : u.getNeighborV().entrySet()) {
        v = a.getKey(); // the neighbor in this iteration

        double alternateDist = u.getDist() + a.getValue();
        if (alternateDist < v.getDist()) { // shorter path to neighbor
          // found
          // System.out.println("+++++");
          q.remove(v);
          v.setDist(alternateDist);
          // System.out.println(v.getId());
          // System.out.println(v.getDist());
          v.setPrevious(u);
          q.add(v);
          // System.out.println(q.size());
        }
      }
    }
  }
Exemplo n.º 24
0
 public static List<Vertex> compute(Graph graph) {
   List<Vertex> resultList = new LinkedList<Vertex>();
   Vertex[] vertexes = graph.getVertexes();
   List<EdgeFrom>[] edgesTo = graph.getEdgesTo();
   double[] d = new double[vertexes.length];
   Arrays.fill(d, Double.MAX_VALUE);
   d[d.length - 1] = 0;
   int[] path = new int[vertexes.length];
   Arrays.fill(path, -1);
   PriorityQueue<State> que = new PriorityQueue<State>();
   que.add(new State(0, vertexes.length - 1));
   while (!que.isEmpty()) {
     State p = que.poll();
     if (d[p.vertex] < p.cost) continue;
     for (EdgeFrom edgeFrom : edgesTo[p.vertex]) {
       if (d[edgeFrom.from] > d[p.vertex] + edgeFrom.weight) {
         d[edgeFrom.from] = d[p.vertex] + edgeFrom.weight;
         que.add(new State(d[edgeFrom.from], edgeFrom.from));
         path[edgeFrom.from] = p.vertex;
       }
     }
   }
   for (int t = 0; t != -1; t = path[t]) {
     resultList.add(vertexes[t]);
   }
   return resultList;
 }
 public static void main(String[] args) throws IOException {
   int n = readInt();
   int[] dogs = new int[n];
   ArrayList<ArrayList<Integer>> adjlist = new ArrayList<ArrayList<Integer>>();
   for (int x = 0; x < n; x++) {
     dogs[x] = readInt();
     adjlist.add(new ArrayList<Integer>());
   }
   int m = readInt();
   for (int x = 0; x < m; x++) {
     int a = readInt() - 1;
     int b = readInt() - 1;
     adjlist.get(a).add(b);
   }
   int time = readInt();
   int[] bark = new int[n];
   PriorityQueue<Dog> moves = new PriorityQueue<Dog>();
   moves.add(new Dog(0, 0));
   bark[0] = 0;
   int[] total = new int[n];
   while (!moves.isEmpty()) {
     Dog curr = moves.poll();
     if (curr.time > time) continue;
     bark[curr.id] = 0;
     total[curr.id]++;
     for (int x = 0; x < adjlist.get(curr.id).size(); x++) {
       int next = adjlist.get(curr.id).get(x);
       if ((bark[next] != 0 && curr.time + dogs[next] > bark[next])) continue;
       moves.remove(new Dog(next, curr.time + dogs[next]));
       bark[next] = curr.time + dogs[next];
       moves.offer(new Dog(next, curr.time + dogs[next]));
     }
   }
   for (int x : total) System.out.println(x);
 }
Exemplo n.º 26
0
 private void expandLandmarkTo() {
   LandmarksToTravelTimeComparator comparator =
       new LandmarksToTravelTimeComparator(this.nodeData, this.landmarkIdx);
   PriorityQueue<Node> pendingNodes = new PriorityQueue<>(100, comparator);
   LandmarksData role = (LandmarksData) this.nodeData.get(this.landmark);
   role.setToLandmarkTravelTime(this.landmarkIdx, 0.0);
   role.setFromLandmarkTravelTime(this.landmarkIdx, 0.0);
   pendingNodes.add(this.landmark);
   while (!pendingNodes.isEmpty()) {
     Node node = pendingNodes.poll();
     double toTravTime =
         ((LandmarksData) this.nodeData.get(node)).getToLandmarkTravelTime(this.landmarkIdx);
     LandmarksData role2;
     for (Link l : node.getInLinks().values()) {
       Node n = l.getFromNode();
       double linkTravTime = this.costFunction.getLinkMinimumTravelDisutility(l);
       role2 = (LandmarksData) this.nodeData.get(n);
       double totalTravelTime = toTravTime + linkTravTime;
       if (role2.getToLandmarkTravelTime(this.landmarkIdx) > totalTravelTime) {
         role2.setToLandmarkTravelTime(this.landmarkIdx, totalTravelTime);
         pendingNodes.add(n);
       }
     }
   }
 }
Exemplo n.º 27
0
  public T receive() {
    lock.lock();
    try {
      while (true) {
        DelayedMessage message = queue.peek();
        if (message == null && stopping) {
          return null;
        }
        if (message == null) {
          condition.await();
          continue;
        }

        long now = timeProvider.getCurrentTime();
        if (message.dispatchTime > now) {
          condition.awaitUntil(new Date(message.dispatchTime));
        } else {
          queue.poll();
          if (queue.isEmpty()) {
            condition.signalAll();
          }
          return message.message;
        }
      }
    } catch (InterruptedException e) {
      throw UncheckedException.throwAsUncheckedException(e);
    } finally {
      lock.unlock();
    }
  }
Exemplo n.º 28
0
  @Override
  public CategoricalResults classify(DataPoint data) {
    CategoricalResults cr = new CategoricalResults(predicting.getNumOfCategories());

    // Use a priority que so that we always pick the two lowest value class labels, makes indexing
    // into the oneVsOne array simple
    PriorityQueue<Integer> options = new PriorityQueue<Integer>(predicting.getNumOfCategories());
    for (int i = 0; i < cr.size(); i++) options.add(i);

    CategoricalResults subRes;
    int c1, c2;
    // We will now loop through and repeatedly pick two combinations, and eliminate the loser, until
    // there is one winer
    while (options.size() > 1) {
      c1 = options.poll();
      c2 = options.poll();

      subRes = oneVone[c1][c2 - c1 - 1].classify(data);

      if (subRes.mostLikely() == 0) // c1 wins, c2 no longer a candidate
      options.add(c1);
      else // c2 wins, c1 no onger a candidate
      options.add(c2);
    }

    cr.setProb(options.peek(), 1.0);

    return cr;
  }
Exemplo n.º 29
0
  private static PencilPosition findShortestRoute(int[][] maze) {
    // all found solutions to the maze
    PriorityQueue<PencilPosition> solutions =
        new PriorityQueue<PencilPosition>(5, new PencilPositionComparator());
    // bread-first search queue
    Queue<PencilPosition> routes = new LinkedList<PencilPosition>();
    // set of already visited positions
    Set<PencilPosition> visitedPositions = new HashSet<PencilPosition>();

    // add the starting positions, which is always (0,0)
    routes.add(new PencilPosition(0, 0, false, null));

    while (!routes.isEmpty()) {
      PencilPosition position = routes.poll();

      // if this is the destinations position then we've found a solution
      if (0 == maze[position.row][position.column]) {
        solutions.add(position);
        continue;
      }

      // if we haven't already visited this position
      if (!visitedPositions.contains(position)) {
        routes.addAll(findPossibleRoutes(position, maze));
        visitedPositions.add(position);
      }
    }

    return solutions.poll();
  }
Exemplo n.º 30
0
  public void PQOrdering() {
    PriorityQueue<String> pq = new PriorityQueue<String>();
    pq.add("5");
    pq.add("3");
    pq.add("1");
    pq.add("2");
    pq.add("4");
    pq.add("6");

    System.out.println("Unordered: " + pq); // Unordered: [1, 2, 3, 5, 4, 6]

    Iterator<String> itr = pq.iterator();
    System.out.print("Unordered Itr: ");
    while (itr.hasNext()) {
      System.out.print(itr.next() + ", "); // Unordered Itr: 1, 2, 3, 5, 4, 6,
    }

    System.out.println("");
    System.out.print("Unordered Arrays: ");
    Object[] obj = pq.toArray();
    for (Object o : obj) {
      System.out.print(o + ", "); // Unordered Arrays: 1, 2, 3, 5, 4, 6,
    }

    // To order a PQ
    System.out.print("\nOrdered:");
    while (!pq.isEmpty()) {
      System.out.print(pq.poll() + ", "); // Ordered: 1, 2, 3, 4, 5, 6,
    }
    System.out.println("********************************************");
  }