Guest User

Untitled

a guest
Jan 4th, 2020
839
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. public List<String> popularNFeatures(int numFeatures, int topFeatures, List<String> possibleFeatures,
  2. int numFeatureRequests, List<String> featureRequests) {
  3. List<String> res = new ArrayList<>();
  4. Set<String> features = new HashSet(possibleFeatures);
  5. Map<String, Word> wordsMap = new HashMap<>();
  6.  
  7. for(int i = 0; i < numFeatureRequests; i++) {
  8. String featureRequest = featureRequests.get(i).replaceAll("[\\!?,;.]", "").toLowerCase();
  9. String[] words = featureRequest.split(" ");
  10.  
  11. for(int j = 0; j < words.length; j++) {
  12. String word = words[j];
  13. if(features.contains(word)) {
  14. Word w;
  15.  
  16. if(wordsMap.containsKey(word))
  17. w = wordsMap.get(word);
  18. else
  19. w = new Word(word, 0);
  20. w.count++;
  21. w.featureRequestIds.add(i);
  22. wordsMap.put(word, w);
  23. }
  24. }
  25. }
  26.  
  27. PriorityQueue<Word> pq = new PriorityQueue<>(new Comparator<Word>() {
  28.  
  29. @Override
  30. public int compare(Word w1, Word w2) {
  31. if(w1.count != w2.count)
  32. return Integer.compare(w2.count, w1.count);
  33. else if(w1.featureRequestIds.size() != w2.featureRequestIds.size())
  34. return Integer.compare(w2.featureRequestIds.size(), w1.featureRequestIds.size());
  35. else
  36. return w1.word.compareTo(w2.word);
  37. }
  38. });
  39.  
  40. pq.addAll(wordsMap.values());
  41.  
  42. if(topFeatures > pq.size()) {
  43. for (int i = 0; i < numFeatures && !pq.isEmpty(); i++)
  44. res.add(pq.poll().word);
  45. } else {
  46. for(int i = 0; i < pq.size(); i++) {
  47. res.add(pq.poll().word);
  48. }
  49. }
  50.  
  51. return res;
  52. }
  53.  
  54. private static class Word {
  55. String word;
  56. int count;
  57. Set<Integer> featureRequestIds;
  58. public Word(String word, int count) {
  59. this.word = word;
  60. this.count = count;
  61. this.featureRequestIds = new HashSet<>();
  62. }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment