/** * Evaluates a query. * * @param queryTree A query tree that has been already transformed with * StructuredRetrieval.transformQuery. * @param requested The number of documents to retrieve, at most. * @return * @throws java.lang.Exception */ public ScoredDocument[] runQuery(Node queryTree, int requested) throws Exception { // my addition queryTree = this.transformQuery(queryTree); // System.out.println("runQuery: " + queryTree.toString()); // construct the query iterators ScoreIterator iterator = (ScoreIterator) createIterator(queryTree); // now there should be an iterator at the root of this tree PriorityQueue<ScoredDocument> queue = new PriorityQueue<ScoredDocument>(); while (!iterator.isDone()) { int document = iterator.nextCandidate(); int length = index.getLength(document); double score = iterator.score(document, length); if (queue.size() <= requested || queue.peek().score < score) { ScoredDocument scoredDocument = new ScoredDocument(document, score); queue.add(scoredDocument); if (queue.size() > requested) { queue.poll(); } } iterator.movePast(document); } return getArrayResults(queue); }
public void add(int x) { if (min.size() <= max.size()) { min.add(x); } else { max.add(x); } }
// 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()); } }
// 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()); } }
// 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()); } }
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(); }
// 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(); }
public double getMedian() { if (smallerElements.size() == largerElements.size()) { return (smallerElements.peek() + largerElements.peek()) / 2.0; } else { return largerElements.peek(); } }
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"); } }
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); } }
public Integer findMedian() { if (min.size() < max.size()) { return max.peek(); } else if (max.size() < min.size()) { return min.peek(); } else { return ((max.peek() + min.peek()) / 2); } }
public ScoredDocument[] getArrayResults(PriorityQueue<ScoredDocument> scores) { ScoredDocument[] results = new ScoredDocument[scores.size()]; for (int i = scores.size() - 1; i >= 0; i--) { results[i] = scores.poll(); } return results; }
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(); } }
private void testCustomAggregation(Long[] values, int n) { PriorityQueue<Long> heap = new PriorityQueue<Long>(n); Arrays.stream(values).filter(x -> x != null).forEach(heap::add); Long[] expected = new Long[heap.size()]; for (int i = heap.size() - 1; i >= 0; i--) { expected[i] = heap.remove(); } testAggregation( Arrays.asList(expected), createLongsBlock(values), createLongRepeatBlock(n, values.length)); }
private void checkNextRequest() { Log.d(TAG, "check next: " + currentRequests.size()); if (currentRequests.size() < maxRequests) { Log.d(TAG, "queue size: " + requestQueue.size()); if (requestQueue.size() > 0) { WebRequest request = requestQueue.remove(); currentRequests.add(request); request.start(); } } }
private void testCustomAggregation(Double[] values, int n) { PriorityQueue<Double> heap = new PriorityQueue<>(n, (x, y) -> -Double.compare(x, y)); Arrays.stream(values).filter(x -> x != null).forEach(heap::add); Double[] expected = new Double[heap.size()]; for (int i = heap.size() - 1; i >= 0; i--) { expected[i] = heap.remove(); } testAggregation( Arrays.asList(expected), createDoublesBlock(values), createLongRepeatBlock(n, values.length)); }
public static void closetPoints(Points[] pointList, PriorityQueue<Points> queue, int k) { for (Points p : pointList) { if (queue.size() == k && p.compareTo(queue.peek()) > 0) queue.poll(); // remove least element, current is better if (queue.size() < k) // we removed one or haven't filled up, so add queue.add(p); } for (Points p : queue) { System.out.print(p + ","); } }
/** * Retrieves and removes the head of this queue, waiting if necessary until an element with an * expired delay is available on this queue, or the specified wait time expires. * * @return the head of this queue, or <tt>null</tt> if the specified waiting time elapses before * an element with an expired delay becomes available * @throws InterruptedException {@inheritDoc} */ public E poll(long timeout, TimeUnit unit) throws InterruptedException { long nanos = unit.toNanos(timeout); final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { for (; ; ) { E first = q.peek(); if (first == null) { if (nanos <= 0) return null; else nanos = available.awaitNanos(nanos); } else { long delay = first.getDelay(TimeUnit.NANOSECONDS); if (delay > 0) { if (nanos <= 0) return null; if (delay > nanos) delay = nanos; long timeLeft = available.awaitNanos(delay); nanos -= delay - timeLeft; } else { E x = q.poll(); assert x != null; if (q.size() != 0) available.signalAll(); return x; } } } } finally { lock.unlock(); } }
public static List<Star> findClosestKStars(int k, ObjectInputStream osin) { // maxHeap to store the closest k stars seen so far. PriorityQueue<Star> maxHeap = new PriorityQueue<>(k, Collections.reverseOrder()); try { while (true) { // Add each star to the max-heap. If the max-heap size exceeds k, // remove the maximum element from the max-heap. Star star = (Star) osin.readObject(); maxHeap.add(star); if (maxHeap.size() == k + 1) { maxHeap.remove(); } } } catch (IOException e) { // Do nothing, read last element in stream. } catch (ClassNotFoundException e) { System.out.println("ClassNotFoundException: " + e.getMessage()); } // We cannot go directly to an ArrayList from PriorityQueue, since // unlike LinkedList, it does not guarantee ordering of entries. List<Star> orderedStars = new ArrayList<Star>(maxHeap); // We need to reverse the orderedStars list since it goes from // largest to smallest because the PriorityQueue used the // Collections.reverse() comparator. Collections.reverse(orderedStars); return orderedStars; }
@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; }
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; }
/** * generates random events to players * * @return String message of random event */ public static String applyRandomEvent() { int rand = (int) (Math.random() * randomEvents.length); Player cp = Configurations.getCurPlayer(); int money = randomEvents[rand].getMoney(); int food = randomEvents[rand].getFood(); int energy = randomEvents[rand].getEnergy(); if (playerOrder.size() == 0) { while (money < 0 || food < 0 || energy < 0) { rand = (int) (Math.random() * randomEvents.length); money = randomEvents[rand].getMoney(); food = randomEvents[rand].getFood(); energy = randomEvents[rand].getEnergy(); } } cp.setMoney(cp.getMoney() + money); cp.setFood(cp.getFood() + food); cp.setEnergy(cp.getEnergy() + energy); if (cp.getMoney() < 0) { cp.setMoney(0); } else if (cp.getFood() < 0) { cp.setFood(0); } else if (cp.getEnergy() < 0) { cp.setEnergy(0); } return randomEvents[rand].getMessage(); }
public void reduce( Text key, Iterator<Text> values, OutputCollector<Text, Text> output, Reporter reporter) throws IOException { while (values.hasNext()) { String line = values.next().toString(); String[] tokens = line.split(","); try { double latitude = (Double.parseDouble(tokens[2])); double longitude = (Double.parseDouble(tokens[3])); Tuple t = new Tuple(longitude, latitude, line); t.setDistance(fp); if (queue.size() < k) { queue.add(t); } else { if (t.distance < queue.peek().distance) { queue.add(t); queue.remove(); } } } catch (Exception c) { } } while (!queue.isEmpty()) { output.collect(new Text("1"), new Text(queue.remove().tupleData)); } }
public Keywords findKeywords(User user, Request request) throws ParseException, IOException { Path dumpFile = dumpSearchResults(user, request); Scanner scanner = new Scanner(dumpFile); TObjectIntHashMap<String> words = new TObjectIntHashMap<>(); while (scanner.hasNextLine()) { String line = scanner.nextLine(); for (String word : StringUtils.tokenize(line, /* Remove stop words */ true)) { if (request.query.contains(word)) continue; Integer cnt = words.get(word); if (cnt == null) { cnt = 1; } else { cnt++; } words.put(word, cnt); } } PriorityQueue<WordAndCount> pq = createPriorityQueue(); words.forEachEntry((a, b) -> pq.add(new WordAndCount(a, b))); scanner.close(); Keywords kw = new Keywords(); WordAndCount[] wc = new WordAndCount[Math.min(request.pageSize, pq.size())]; for (int i = 0; i < wc.length; i++) wc[i] = pq.poll(); kw.keywords = wc; return kw; }
/** * Adds {@code value} to this heap if it is larger than any of the current elements. Returns * {@code true} if {@code value} was added. */ private boolean maybeAddInput(T value) { if (maximumSize == 0) { // Don't add anything. return false; } // If asQueue == null, then this is the first add after the latest call to the // constructor or asList(). if (asQueue == null) { asQueue = new PriorityQueue<>(maximumSize, compareFn); for (T item : asList) { asQueue.add(item); } asList = null; } if (asQueue.size() < maximumSize) { asQueue.add(value); return true; } else if (compareFn.compare(value, asQueue.peek()) > 0) { asQueue.poll(); asQueue.add(value); return true; } else { return false; } }
static void test00() { Aron.beg(); PriorityQueue<Interval> queue = new PriorityQueue<Interval>(); Stack<Interval> stack = new Stack<Interval>(); int[] arr1 = {4, 1, 2, 6, 9}; int[] arr2 = {5, 1, 4, 9, 10}; for (int i = 0; i < arr1.length; i++) { queue.add(new Interval(arr1[i], arr2[i])); } if (queue.size() > 0) { stack.push(queue.remove()); } while (!queue.isEmpty()) { Interval top = stack.peek(); Interval inter = queue.remove(); if (top.end < inter.begin) stack.push(inter); else { stack.peek().end = Math.max(stack.peek().end, inter.end); } } while (!stack.empty()) { System.out.println("[" + stack.peek().begin + " " + stack.peek().end + "]"); stack.pop(); } Aron.end(); }
@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; }
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; }
/** * 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); }
public void solve(int testNumber, InputReader in, OutputWriter out) { String X; PriorityQueue<Integer> pq = new PriorityQueue<>(); Stack<Integer> stack = new Stack<>(); while ((X = in.next()) != null) { int x = Integer.valueOf(X); pq.add(x); int sz = pq.size(); int median = 0; if (sz == 1) { median = pq.peek(); } else { for (int i = 0; i <= sz / 2; i++) { stack.add(pq.poll()); if ((i == (sz / 2) - 1 && sz % 2 == 0) || i == (sz / 2)) { median += stack.peek(); } } if (sz % 2 == 0) median /= 2; } while (!stack.isEmpty()) pq.add(stack.pop()); out.printLine(median); } }