示例#1
0
  public List<Task> mockRunTaks(List<Task> tasks) {
    PriorityQueue<Task> taskQueue =
        new PriorityQueue<Task>(
            new Comparator<Task>() {
              @Override
              public int compare(Task t1, Task t2) {
                return t1.priority - t2.priority;
              }
            });
    List<Task> runOrder = new ArrayList<Task>();
    HashMap<Task, Integer> taskIndegrees = new HashMap<Task, Integer>();

    for (Task task : tasks) {
      taskIndegrees.put(task, task.dependencies.size());
      if (task.dependencies.size() == 0) {
        taskQueue.offer(task);
      }
    }
    while (!taskQueue.isEmpty()) {
      Task curTask = taskQueue.poll();
      runOrder.add(curTask);

      for (Task task : curTask.dependencies) {
        taskIndegrees.put(task, taskIndegrees.get(task) - 1);
        if (taskIndegrees.get(task) == 0) taskQueue.offer(task);
      }
    }

    return runOrder;
  }
示例#2
0
  // Adds a number into the data structure.
  public void addNum(int num) {
    minHeap.offer(num);

    if (minHeap.size() - maxHeap.size() > 1) {
      maxHeap.offer(minHeap.poll());
    }
  }
示例#3
0
 // Time: O(n*logk)
 // Space: O(k)
 // Use min heap to store current end time of each room.
 // If current interval start time is smaller than the minimum end time,
 // create a new room (add end time to the heap)
 // Else, update the minimum end time
 // Return the size of heap
 public int minMeetingRooms(Interval[] intervals) {
   if (intervals == null || intervals.length == 0) return 0;
   Arrays.sort(
       intervals,
       new Comparator<Interval>() {
         @Override
         public int compare(Interval i1, Interval i2) {
           return i1.start - i2.start;
         }
       });
   PriorityQueue<Integer> heap = new PriorityQueue<Integer>();
   for (Interval interval : intervals) {
     if (heap.size() == 0) {
       heap.offer(interval.end);
     } else {
       if (interval.start < heap.peek()) {
         heap.offer(interval.end);
       } else {
         heap.poll();
         heap.offer(interval.end);
       }
     }
   }
   return heap.size();
 }
示例#4
0
  public ListNode mergeKLists(ArrayList<ListNode> lists) {
    if (lists == null || lists.isEmpty()) return null;
    ListNode head = new ListNode(0);
    ListNode p = head;

    PriorityQueue<ListNode> queue =
        new PriorityQueue<ListNode>(
            lists.size(),
            new Comparator<ListNode>() {

              @Override
              public int compare(ListNode o1, ListNode o2) {
                return o1.val - o2.val;
              }
            });
    for (ListNode n : lists) {
      if (n != null) {
        queue.offer(n);
      }
    }

    while (!queue.isEmpty()) {
      ListNode n = queue.poll();
      p.next = n;
      p = p.next;
      if (n.next != null) {
        queue.offer(n.next);
      }
    }

    return head.next;
  }
示例#5
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;
  }
 // 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());
   }
 }
 /**
  * Method3: Find the next element from the heap, and add new element into heap from current
  * element's down(if j == 0) and right.
  *
  * @param int[] nums1, int[] nums2, int k
  * @return List<int[]> Time: O(k * (log(k) + 2log(k))) one poll and two offer Space: O(k)
  */
 public List<int[]> findKPairswithSmallestSumsII(int[] nums1, int[] nums2, int k) {
   List<int[]> result = new ArrayList<>();
   if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) {
     return result;
   }
   PriorityQueue<Pair> heap =
       new PriorityQueue<>(
           k,
           new Comparator<Pair>() {
             @Override
             public int compare(Pair a, Pair b) {
               return a.sum - b.sum;
             }
           });
   // init
   heap.offer(new Pair(0, 0, nums1[0] + nums2[0]));
   // find first k
   while (!heap.isEmpty() && k-- > 0) {
     Pair temp = heap.poll();
     if (temp.i + 1 < nums1.length && temp.j == 0) { // if (j == 0) add down element
       heap.offer(new Pair(temp.i + 1, temp.j, nums1[temp.i + 1] + nums2[temp.j]));
     }
     if (temp.j + 1 < nums2.length) {
       heap.offer(new Pair(temp.i, temp.j + 1, nums1[temp.i] + nums2[temp.j + 1]));
     }
     result.add(new int[] {nums1[temp.i], nums2[temp.j]});
   }
   return result;
 }
示例#8
0
 public int minMeetingRooms(Interval[] intervals) {
   Arrays.sort(intervals, new IntervalComparator());
   PriorityQueue<Integer> roomQueue = new PriorityQueue<Integer>();
   int num = 0;
   for (int i = 0; i < intervals.length; i++) {
     if (roomQueue.isEmpty()) {
       num++;
       System.out.println(intervals[i].end);
       roomQueue.offer(intervals[i].end);
     } else {
       int minEnd = roomQueue.peek();
       System.out.println("minEnd: " + minEnd);
       if (intervals[i].start < minEnd) {
         System.out.println("new offering " + intervals[i].end);
         num++;
         roomQueue.offer(intervals[i].end);
       } else {
         System.out.println("substitude " + intervals[i].end);
         roomQueue.poll();
         roomQueue.offer(intervals[i].end);
       }
     }
   }
   return num;
 }
示例#9
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());
   }
 }
示例#10
0
  public static SearchResult generic(SearchProblem prob, Comparator<SearchNode> cmp) {
    PriorityQueue<SearchNode> frontier = new PriorityQueue<SearchNode>(10000, cmp);
    frontier.offer(prob.startNode());

    Set<State> explored = new HashSet<State>();

    while (!frontier.isEmpty()) {
      SearchNode candidate = frontier.poll();

      if (candidate.isGoal()) {
        return new SearchResult(candidate, explored.size(), frontier.size());
      }

      List<Action> nextActions = prob.actions(candidate.state);
      for (Action action : nextActions) {
        SearchNode child = prob.childNode(candidate, action);
        if (!explored.contains(child.state)) {
          frontier.offer(child);
          explored.add(candidate.state);
        }
      }
    }

    return null;
  }
  /*skylineII
  * 		// First: split building into two edge and sort
  // Second: create a max-heap with first height 0, we offer height and poll height
  // Third: for every edge, - put in(new skyline), + remove it(old skyline), if current max height not the same as before we add in
  // init 0, max height so far, if change, skyline redraw		//
  * */
  public List<int[]> skylineII(List<Interval> intervals) {
    List<int[]> res = new ArrayList<int[]>();
    if (intervals == null || intervals.size() == 0) {
      return res;
    }
    // First: split building into two edge and sort
    List<int[]> height = new ArrayList<int[]>();
    for (Interval item : intervals) {
      height.add(new int[] {item.start, -item.height}); // start, -height
      height.add(new int[] {item.end, item.height}); // end, height
    }
    Collections.sort(
        height,
        new Comparator<int[]>() {
          public int compare(int[] a, int[] b) {
            if (a[0] != b[0]) return a[0] - b[0];
            return a[1] - b[1]; // start BEFORE end, height small BEFORE height large
            // BOTH START -10,-5=> -10->-5
            // BOTH END 10, 5=>5->10
          }
        });
    // Second: create a max-heap with first height 0, we offer height and poll height
    // 根据position从前到后扫描每一个edge
    // 将edge根据是入还是出来将当前height加入或者移除heap
    // 再得到当前最高点(max-heap)来决定是否加入最终结果。

    // 把所有的turning points 放在一起,根据coordination从小到大sort 。
    // 再用max-heap, 把所有的turning points扫一遍,遇到start turning point,
    // 把 volume放入max-heap.
    // 遇到end turning point,把对应的volume从max-heap中取出。
    // max-heap的max 值就是对应区间的最大volume
    // Input : [2,-10][3,-15][5,-12][7,15][9,10][12,12][15,-10][19,-8][20,10][24,8]
    // Result: [2 10],[3 15],[7 12],[12 0],[15 10],[20 8],[24, 0]
    // Event{true,0,200}, Event{false,10,200}
    // ==> Event{0,200}, Event{10,-200}
    // 按照time排序,time相同,is_in = false的优先
    // 然后你扫过去, is_in=true的你就加mem,is_in=false的你就-mem.每个事件点,
    // 你会加或减一次,每加或减一次后,就check是不是超过总的
    PriorityQueue<Integer> pq = new PriorityQueue<Integer>(10, new pqComparator());
    // Avoid empty heap, still has ZERO value
    pq.offer(0);
    int prev = 0;
    // Third: for every edge, - put in(new skyline), + remove it(old skyline), if current max height
    // not the same as before we add in
    // init 0, max height so far, if change, skyline redraw
    for (int[] item : height) {
      // START, ADD
      if (item[1] < 0) pq.offer(-item[1]);
      // END, REMOVE
      else pq.remove(item[1]);
      int max = pq.peek();
      if (prev != max) {
        res.add(new int[] {item[0], max});
        prev = max;
      }
    }
    return res;
  }
示例#12
0
 /**
  * initial for routing, if the start node is an intersect, then it should already in the adjlist,
  * than we just add it. If the start node is not intersect, then the node will not in adjlist, we
  * need find the node's two edge entrance if the edge is bidirection or one edge entrance if the
  * edge is oneway.
  *
  * @param startNode
  * @param endNode
  * @param startTime
  * @param dayIndex
  * @param nodeHelperCache
  */
 public static PriorityQueue<NodeInfoHelper> initialStartSet(
     long startNode,
     long endNode,
     int startTime,
     int dayIndex,
     HashMap<Long, NodeInfoHelper> nodeHelperCache) {
   PriorityQueue<NodeInfoHelper> openSet =
       new PriorityQueue<NodeInfoHelper>(
           10000,
           new Comparator<NodeInfoHelper>() {
             public int compare(NodeInfoHelper n1, NodeInfoHelper n2) {
               return (int) (n1.getTotalCost() - n2.getTotalCost());
             }
           });
   NodeInfo start = OSMData.nodeHashMap.get(startNode);
   NodeInfoHelper current;
   // initial start end set
   if (start.isIntersect()) {
     // initial
     current = new NodeInfoHelper(startNode);
     current.setCost(0);
     current.setCurrentLevel(10);
     current.setHeuristic(OSMRouting.estimateHeuristic(startNode, endNode));
     openSet.offer(current); // push the start node
     nodeHelperCache.put(current.getNodeId(), current); // add cache
   } else {
     EdgeInfo edge = start.getOnEdgeList().getFirst();
     double travelTime = 1; // second
     int distance; // feet
     int totalDistance = edge.getDistance(); // feet
     if (!edge.isOneway()) {
       // distance from start to middle
       distance = edge.getStartDistance(startNode);
       travelTime = edge.getTravelTime(startTime, dayIndex, false);
       travelTime *= (double) distance / totalDistance;
       travelTime /= OSMParam.MILLI_PER_SECOND;
       current = new NodeInfoHelper(edge.getStartNode());
       current.setCost(travelTime);
       current.setCurrentLevel(10);
       current.setHeuristic(OSMRouting.estimateHeuristic(edge.getStartNode(), endNode));
       openSet.offer(current); // push the start node
       nodeHelperCache.put(current.getNodeId(), current); // add cache
     }
     // distance from middle to end
     distance = edge.getEndDistance(startNode);
     travelTime = edge.getTravelTime(startTime, dayIndex, true);
     travelTime *= (double) distance / totalDistance;
     current = new NodeInfoHelper(edge.getEndNode());
     current.setCost(travelTime);
     current.setCurrentLevel(10);
     current.setHeuristic(OSMRouting.estimateHeuristic(edge.getEndNode(), endNode));
     openSet.offer(current); // push the start node
     nodeHelperCache.put(current.getNodeId(), current); // add cache
   }
   return openSet;
 }
示例#13
0
 public PriorityQueue<Run> getPQ() {
   PriorityQueue<Run> temp1 = new PriorityQueue<Run>();
   PriorityQueue<Run> temp2 = new PriorityQueue<Run>();
   while (!runs.isEmpty()) {
     Run r = runs.poll();
     temp1.offer(r);
     temp2.offer(r);
   }
   runs = temp1;
   return temp2;
 }
示例#14
0
 public static void main(String[] args) {
   PriorityQueue pq = new PriorityQueue();
   // 下面代码依次向pq中加入四个元素
   pq.offer(6);
   pq.offer(-3);
   pq.offer(9);
   pq.offer(0);
   // 输出pq队列,并不是按元素的加入顺序排列,而是按元素的大小顺序排列
   System.out.println(pq);
   // 访问队列第一个元素,其实就是队列中最小的元素:-3
   System.out.println(pq.peek());
 }
示例#15
0
 public static void main(String[] args) {
   PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
   pq.offer(6);
   pq.offer(-3);
   pq.offer(9);
   pq.offer(0);
   System.out.println(pq);
   while (pq.peek() != null) {
     System.out.print(pq.poll() + ", ");
   }
   System.out.println();
 }
  static void sweep(ArrayList<Integer> indexes) {
    PriorityQueue<Event> pq = new PriorityQueue<Event>();
    for (int i = 0; i < indexes.size(); i++) {
      pq.offer(new Event(lo[val[indexes.get(i)]] + 1, 1, indexes.get(i)));
      pq.offer(new Event(hi[val[indexes.get(i)]], -1, indexes.get(i)));
    }

    TreeSet<Integer> active = new TreeSet<Integer>();
    while (!pq.isEmpty()) {
      Event curr = pq.poll();
      if (curr.type == 1) active.add(curr.index);
      else if (curr.type == -1) {
        active.remove(curr.index);
        Integer lower = active.lower(curr.index);
        if (lower != null && lower > lo[val[curr.index]]) {
          Interval add = new Interval(lower, curr.index);
          Interval prev = intervals.floor(add);
          Interval next = intervals.ceiling(add);
          boolean intersectPrev = true;
          boolean intersectNext = true;

          if (prev != null) {
            if (Math.max(add.l, prev.l) < Math.min(add.r, prev.r)) {
              if (add.r - add.l <= prev.r - prev.l) {
                intervals.remove(prev);
                intersectPrev = false;
              }
            } else {
              intersectPrev = false;
            }
          } else {
            intersectPrev = false;
          }

          if (next != null) {
            if (Math.max(add.l, next.l) < Math.min(add.r, next.r)) {
              if (add.r - add.l <= next.r - next.l) {
                intervals.remove(next);
                intersectNext = false;
              }
            } else {
              intersectNext = false;
            }
          } else {
            intersectNext = false;
          }

          if (!intersectPrev && !intersectNext) intervals.add(add);
        }
      }
    }
  }
示例#17
0
  public List<Integer> topKFrequent(int[] nums, int k) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int num : nums) {
      if (map.containsKey(num)) {
        map.put(num, map.get(num) + 1);
      } else {
        map.put(num, 1);
      }
    }

    PriorityQueue<Pair> pq =
        new PriorityQueue<Pair>(
            new Comparator<Pair>() {
              public int compare(Pair o1, Pair o2) {
                return o2.count - o1.count;
              }
            });

    for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
      Pair p = new Pair(entry.getKey(), entry.getValue());
      pq.offer(p);
      //            if (pq.size() > k) {
      //                pq.poll();
      //            }
    }

    List<Integer> result = new ArrayList<>();

    for (int i = 0; i < k; i++) {
      result.add(pq.poll().number);
    }

    // Collections.reverse(result);
    return result;
  }
示例#18
0
  public Authenticator(Server se) {
    server = se;

    for (int i = 0; i < MAX_GUEST_PLAYERS; ) {
      freeGuestNumbers.offer((short) ++i);
    }

    try {
      minecraftNet = new URL(MINECRAFT_AUTH_URL);
    } catch (MalformedURLException e1) {
      e1.printStackTrace();
    }

    try {
      shaMD = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException nsae) {
      System.out.println(
          "Attention: Seems like MessageDigest is missing in your Java installation...");
    }

    if (useCustAuth()) {
      timer = new Timer();
      timer.schedule(new MinecraftOnlineChecker(this), 0, REFRESH_TIME * 1000);
    }
  }
示例#19
0
文件: Arene.java 项目: clem822/bl
  /**
   * Renvoie la liste des personnages tries pour le classement final : les vivants ne sont pas
   * classes et les morts sont classes par ordre du tour ou ils sont morts.
   *
   * @return liste des personnages ordonnes pour le classement final
   */
  private List<VuePersonnage> getPersonnagesClassement() {
    PriorityQueue<VuePersonnage> classement = new PriorityQueue<VuePersonnage>();

    // recuperation des personnages en vie
    for (VuePersonnage vuePers : personnages.values()) {
      classement.offer(vuePers);
    }

    // recuperation des personnages elimines
    for (VuePersonnage vuePers : personnagesMorts) {
      classement.offer(vuePers);
    }

    // retour sous forme de liste pour les futures utilisations
    return new ArrayList<VuePersonnage>(classement);
  }
 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();
 }
 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);
 }
 /**
  * Method1: Brute Force + Heap
  *
  * @param int[] nums1, int[] nums2, int k
  * @return List<int[]> Time: O(m * n) Space: O(m * n)
  */
 public List<int[]> findKPairswithSmallestSums(int[] nums1, int[] nums2, int k) {
   List<int[]> result = new ArrayList<>();
   if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) {
     return result;
   }
   // offer pair in minHeap
   PriorityQueue<Pair> heap =
       new PriorityQueue<>(
           k,
           new Comparator<Pair>() {
             @Override
             public int compare(Pair a, Pair b) {
               return a.sum - b.sum;
             }
           });
   for (int i = 0; i < nums1.length; i++) {
     for (int j = 0; j < nums2.length; j++) {
       heap.offer(new Pair(i, j, nums1[i] + nums2[j]));
     }
   }
   // poll first k pair from heap
   for (int i = 0; i < k && !heap.isEmpty(); i++) { // be careful about case heap.size() < k
     Pair res = heap.poll();
     result.add(new int[] {nums1[res.i], nums2[res.j]});
   }
   return result;
 }
示例#23
0
  @SuppressWarnings("deprecation")
  @Override
  public boolean queueBlockBreakEffect(
      Platform server, Vector position, int blockId, double priority) {
    if (taskId == -1) {
      taskId =
          server.schedule(
              0,
              1,
              new Runnable() {
                @Override
                public void run() {
                  int max = Math.max(1, Math.min(30, effectQueue.size() / 3));
                  for (int i = 0; i < max; ++i) {
                    if (effectQueue.isEmpty()) return;

                    effectQueue.poll().play();
                  }
                }
              });
    }

    if (taskId == -1) {
      return false;
    }

    effectQueue.offer(new QueuedEffect(position, blockId, priority));

    return true;
  }
示例#24
0
  public static void sort(Integer[] a) {
    PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();

    for (int i = 0; i < a.length; i++) priorityQueue.offer(a[i]);

    for (int i = 0; i < a.length; i++) a[i] = priorityQueue.poll();
  }
示例#25
0
  private void cornerEdgeCollision(Corner corner, Edge edge) {
    // check for the uphill vector of both edges being too similar (parallel
    // edges)
    // also rejects e == corner.nextL or corner.prevL
    // updated to take into account vertical edges - will always have same
    // uphill! - (so we check edge direction too)
    if ((edge.uphill.angle(corner.prevL.uphill) < 0.0001
            && edge.direction().angle(corner.prevL.uphill) < 0.0001)
        || (edge.uphill.angle(corner.nextL.uphill) < 0.0001
            && edge.direction().angle(corner.nextL.uphill) < 0.0001)) return;

    Tuple3d res = null;
    try {
      // sometimes locks up here if edge.linear form has NaN components.
      if (corner.prevL.linearForm.hasNaN()
          || corner.nextL.linearForm.hasNaN()
          || edge.linearForm.hasNaN()) throw new Error();
      res = edge.linearForm.collide(corner.prevL.linearForm, corner.nextL.linearForm);
    } catch (Throwable f) {
      // trying to collide parallel-ish faces, don't bother
      // System.err.println( "didn't like colliding " + edge + " and " +
      // corner.prevL + " and " + corner.nextL );
      return;
    }

    if (res != null) {
      // cheap reject: if collision is equal or below (not the correct
      // place to check) the corner, don't bother with it
      if (res.z < corner.z || res.z < edge.start.z) return;

      EdgeCollision ec = new EdgeCollision(new Point3d(res), corner.prevL, corner.nextL, edge);

      if (!skel.seen.contains(ec)) faceEvents.offer(ec);
    }
  }
示例#26
0
    RocksDBMergeIterator(
        List<Tuple2<RocksIterator, Integer>> kvStateIterators, final int keyGroupPrefixByteCount) {
      Preconditions.checkNotNull(kvStateIterators);
      this.keyGroupPrefixByteCount = keyGroupPrefixByteCount;

      Comparator<MergeIterator> iteratorComparator = COMPARATORS.get(keyGroupPrefixByteCount);

      if (kvStateIterators.size() > 0) {
        this.heap = new PriorityQueue<>(kvStateIterators.size(), iteratorComparator);

        for (Tuple2<RocksIterator, Integer> rocksIteratorWithKVStateId : kvStateIterators) {
          RocksIterator rocksIterator = rocksIteratorWithKVStateId.f0;
          rocksIterator.seekToFirst();
          if (rocksIterator.isValid()) {
            heap.offer(new MergeIterator(rocksIterator, rocksIteratorWithKVStateId.f1));
          } else {
            rocksIterator.close();
          }
        }

        kvStateIterators.clear();

        this.valid = !heap.isEmpty();
        this.currentSubIterator = heap.poll();
      } else {
        // creating a PriorityQueue of size 0 results in an exception.
        this.heap = null;
        this.valid = false;
      }

      this.newKeyGroup = true;
      this.newKVState = true;
    }
示例#27
0
 public static String[] getBestMatches(String[] members, String currentUser, int sf) {
   Member allMember[] = new Member[members.length];
   int index = -1;
   for (int i = 0; i < allMember.length; i++) {
     Scanner in = new Scanner(members[i]);
     allMember[i] = new Member(i, in.next(), in.next(), in.next(), in.nextLine());
     if (allMember[i].name.compareTo(currentUser) == 0) {
       index = i;
     }
   }
   PriorityQueue<Member> order = new PriorityQueue<Member>();
   for (int i = 0; i < allMember.length; i++) {
     if (i != index && allMember[i].gender.compareTo(allMember[index].requestedGender) == 0) {
       int count = 0;
       for (int j = 1; j < allMember[i].answer.length(); j += 2) {
         if (allMember[i].answer.charAt(j) == allMember[index].answer.charAt(j)) {
           count++;
         }
       }
       if (count >= sf) {
         allMember[i].similar = count;
         order.offer(allMember[i]);
       }
     }
   }
   String result[] = new String[order.size()];
   for (int i = 0; i < result.length; i++) {
     result[i] = order.poll().name;
   }
   return result;
 }
示例#28
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);
        }
      }
    }
示例#29
0
 /**
  * using low bound for travel time, for reverse searching
  *
  * @param endNode
  * @param startNode
  * @param openSet
  * @param nodeHelperCache
  */
 public void initialEndSet(
     long startNode,
     long endNode,
     PriorityQueue<NodeInfoHelper> openSet,
     HashMap<Long, NodeInfoHelper> nodeHelperCache) {
   NodeInfo start = OSMData.nodeHashMap.get(startNode);
   NodeInfoHelper current;
   // initial start end set
   if (start.isIntersect()) {
     // initial
     current = new NodeInfoHelper(startNode);
     current.setCost(0);
     current.setCurrentLevel(10);
     current.setHeuristic(OSMRouting.estimateHeuristic(startNode, endNode));
     openSet.offer(current); // push the start node
     nodeHelperCache.put(current.getNodeId(), current); // add cache
   } else {
     EdgeInfo edge = start.getOnEdgeList().getFirst();
     double travelTime = 1; // second
     int distance; // feet
     int totalDistance = edge.getDistance(); // feet
     if (!edge.isOneway()) {
       // distance from start to middle
       distance = edge.getStartDistance(startNode);
       // get low bound of travel time
       travelTime = edge.getTravelTimeMin(false);
       travelTime *= (double) distance / totalDistance;
       current = new NodeInfoHelper(edge.getStartNode());
       current.setCost(travelTime);
       current.setCurrentLevel(10);
       current.setHeuristic(OSMRouting.estimateHeuristic(edge.getStartNode(), endNode));
       openSet.offer(current); // push the start node
       nodeHelperCache.put(current.getNodeId(), current); // add cache
     }
     // distance from middle to end
     distance = edge.getEndDistance(startNode);
     travelTime = edge.getTravelTimeMin(true);
     travelTime *= (double) distance / totalDistance;
     current = new NodeInfoHelper(edge.getEndNode());
     current.setCost(travelTime);
     current.setCurrentLevel(10);
     current.setHeuristic(OSMRouting.estimateHeuristic(edge.getEndNode(), endNode));
     openSet.offer(current); // push the start node
     nodeHelperCache.put(current.getNodeId(), current); // add cache
   }
 }
示例#30
0
  public void expandVertex(
      Node target,
      TimeEntry removed,
      HashMap<Long, Integer> wasTraversed,
      PriorityQueue<TimeEntry> queue,
      HashMap<Long, RouteEntry> parents) {

    Long2IntMap neig = graph.accessNeighborhood(graph.getNode(removed.getId()));

    for (long vid : neig.keySet()) {

      int arrivalTime = graph.getArrival(removed.getArrivalTime(), neig.get(vid));
      int travelTime = removed.getTravelTime() + neig.get(vid);
      TimeEntry newEntry = new TimeEntry(vid, travelTime, arrivalTime, removed.getId());

      Edge edge = null;
      int distance = -1;

      if (!wasTraversed.containsKey(vid)) {

        queue.offer(newEntry);
        wasTraversed.put(newEntry.getId(), newEntry.getTravelTime());

        distance = neig.get(vid);
        edge = getEdge(removed.getId(), vid, distance);
        parents.put(
            vid, new RouteEntry(removed.getId(), distance / 17, edge.getId(), edge.getLabel()));
      } else {

        int cost = wasTraversed.get(vid);

        if (cost != wasRemoved && cost > newEntry.getTravelTime()) {
          queue.remove(newEntry);
          queue.offer(newEntry);
          wasTraversed.remove(newEntry.getId());
          wasTraversed.put(newEntry.getId(), newEntry.getTravelTime());

          parents.remove(vid);
          distance = neig.get(vid);
          edge = getEdge(removed.getId(), vid, distance);
          parents.put(
              vid, new RouteEntry(removed.getId(), distance / 17, edge.getId(), edge.getLabel()));
        }
      }
    }
  }