Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Last active September 18, 2022 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shixiaoyu/cfb128c356e6b0654f1578ac84823b00 to your computer and use it in GitHub Desktop.
Save shixiaoyu/cfb128c356e6b0654f1578ac84823b00 to your computer and use it in GitHub Desktop.
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
public class FoodRatings {
private class Food implements Comparable<Food>{
// skip boilerplate getter/setters
public String food;
public String cuisine;
public int rating;
public Food(String food, String cuisine, int rating) {
this.food = food;
this.cuisine = cuisine;
this.rating = rating;
}
@Override
public int compareTo(Food o) {
assert o != null;
if (o.rating == this.rating) {
return this.food.compareTo(o.food);
}
return o.rating - this.rating; }
}
// food -> Food
private Map<String, Food> foodIndex = new HashMap<>();
// cuisine -> MaxHeap on rating
private Map<String, Queue<Food>> cuisineIndex = new HashMap<>();
public FoodRatings(String[] foods, String[] cuisines, int[] ratings) {
for (int i = 0; i < foods.length; i++) {
Food f = new Food(foods[i], cuisines[i], ratings[i]);
// given food is distinct
this.foodIndex.put(f.food, f);
/* use putIfAbsent instead
if (!this.cuisineIndex.containsKey(f.cuisine)) {
this.cuisineIndex.put(f.cuisine, new PriorityQueue<>());
}
*/
this.cuisineIndex.putIfAbsent(f.cuisine, new PriorityQueue<>());
this.cuisineIndex.get(f.cuisine).add(f);
}
}
public void changeRating(String food, int newRating) {
Food f = this.foodIndex.get(food);
f.rating = newRating;
// need to update the max heap by deleting and re-inserting
this.cuisineIndex.get(f.cuisine).remove(f);
this.cuisineIndex.get(f.cuisine).add(f);
}
public String highestRated(String cuisine) {
return this.cuisineIndex.get(cuisine).peek().food;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment