Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Display Page (Pagination)
//'main' method must be in a class 'Rextester'. //Compiler version 1.8.0_111 import java.util.*; import java.lang.*; class Rextester { public static void main(String args[]) { //hostId, ListId, points, city List<String> input = new ArrayList<>(); input.add("1,28,310.6,SF"); input.add("1,5,204.1,SF"); input.add("20,7,203.2,Oakland"); input.add("6,8,202.2,SF"); input.add("6,10,199.1,SF"); input.add("1,16,190.4,SF"); input.add("6,29,185.2,SF"); input.add("7,20,180.1,SF"); input.add("6,21,162.1,SF"); input.add("2,18,161.2,SF"); input.add("2,30,149.1,SF"); input.add("3,76,146.2,SF"); input.add("2,14,141.1,San Jose"); List<String> result = displayPages(input, 5); for (int i = 0; i < result.size(); i++) { System.out.println(result.get(i) + "\n"); } } static class RecordNode { int hostId, listId; double score; String record; public RecordNode(String record) { String[] tokens = record.split(","); hostId = Integer.valueOf(tokens[0]); listId = Integer.valueOf(tokens[1]); score = Double.valueOf(tokens[2]); this.record = record; } } // different hostId into different deque // put all deque into a priority queue sorted by the score of the head of queue // pop pageSize element from priority queue to form a page // put back the popped element back into priority queue with head element removed if not empty public static List<String> displayPages(List<String> records, int size) { Map<Integer, Deque<RecordNode>> map = new HashMap<>(); for (String s: records) { RecordNode node = new RecordNode(s); if (!map.containsKey(node.hostId)) map.put(node.hostId, new ArrayDeque<>()); map.get(node.hostId).offerLast(node); } PriorityQueue<Deque<RecordNode>> pq = new PriorityQueue<>((a, b) -> b.peekFirst().score > a.peekFirst().score ? 1 : -1); for (Deque<RecordNode> i: map.values()) pq.offer(i); List<String> pages = new ArrayList<>(); List<String> lines = new ArrayList<>(); while (!pq.isEmpty()) { List<Deque<RecordNode>> hold = new ArrayList<>(); while (lines.size() < size && !pq.isEmpty()) { lines.add(pq.peek().peekFirst().record); hold.add(pq.poll()); } if (lines.size() == size) { pages.add(String.join("\n", lines)); lines.clear(); } for (Deque<RecordNode> i: hold) { i.pollFirst(); if (!i.isEmpty()) pq.offer(i); } } if (!lines.isEmpty()) pages.add(String.join("\n", lines)); return pages; } }
run
|
edit
|
history
|
help
0
Merge Sort in Java
mp1
Remove punctuation except numbers, commas and spaces
cuboid volume
Coding Challenge - 01 (Even numbers)
add2
pourWater
Problem: binary
VENU DEVELOPMENTS
Lexisort