Skip to content

Instantly share code, notes, and snippets.

@chrislzm
Last active April 19, 2018 09:07
Show Gist options
  • Save chrislzm/10f03430b6b4966e5339c8cbc59b6caa to your computer and use it in GitHub Desktop.
Save chrislzm/10f03430b6b4966e5339c8cbc59b6caa to your computer and use it in GitHub Desktop.
class PaginateListings {
static class Listing {
Float score;
String hostId;
String listing;
Listing(float s, String h, String l) {
score = s;
hostId = h;
listing = l;
}
}
static class Host {
String hostId;
LinkedList<Listing> listings = new LinkedList<>();
Host(String s) {
hostId = s;
}
}
static Listing getListingFromString(String s) {
String[] fields = s.split(",");
String hostId = fields[0];
float score = Float.parseFloat(fields[2]);
return new Listing(score,hostId,s);
}
static List<String> getSortedPages(ArrayList<String> listings, int perPage) {
Set<String> set = new HashSet<>();
PriorityQueue<Host> duplicates = new PriorityQueue<>((a,b)->b.listings.getFirst().score.compareTo(a.listings.getFirst().score));
Map<String,Host> map = new HashMap<>();
List<String> output = new ArrayList<>();
int count = 0;
for(int i=1; i<listings.size(); i++) {
if(count > 0 && count % perPage == 0) {
set.clear();
count = 0;
LinkedList<Host> temp = new LinkedList<>();
while(!duplicates.isEmpty()) {
Host h = duplicates.poll();
output.add(h.listings.removeFirst().listing);
set.add(h.hostId);
temp.add(h);
count++;
}
while(!temp.isEmpty()) {
Host h = temp.removeFirst();
if(h.listings.size() > 0) {
duplicates.add(h);
}
}
}
Listing l = getListingFromString(listings.get(i));
if(!set.contains(l.hostId)) {
output.add(l.listing);
set.add(l.hostId);
count++;
} else {
Host h = map.computeIfAbsent(l.hostId, k->new Host(l.hostId));
h.listings.add(l);
if(h.listings.size() == 1) { // Not in priority queue
duplicates.add(h);
}
}
}
while(!duplicates.isEmpty()) {
Host h = duplicates.poll();
output.add(h.listings.removeFirst().listing);
if(h.listings.size() > 0) {
duplicates.add(h);
}
}
return output;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment