Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public List<String> popularNFeatures(int numFeatures, int topFeatures, List<String> possibleFeatures,
- int numFeatureRequests, List<String> featureRequests) {
- List<String> res = new ArrayList<>();
- Set<String> features = new HashSet(possibleFeatures);
- Map<String, Word> wordsMap = new HashMap<>();
- for(int i = 0; i < numFeatureRequests; i++) {
- String featureRequest = featureRequests.get(i).replaceAll("[\\!?,;.]", "").toLowerCase();
- String[] words = featureRequest.split(" ");
- for(int j = 0; j < words.length; j++) {
- String word = words[j];
- if(features.contains(word)) {
- Word w;
- if(wordsMap.containsKey(word))
- w = wordsMap.get(word);
- else
- w = new Word(word, 0);
- w.count++;
- w.featureRequestIds.add(i);
- wordsMap.put(word, w);
- }
- }
- }
- PriorityQueue<Word> pq = new PriorityQueue<>(new Comparator<Word>() {
- @Override
- public int compare(Word w1, Word w2) {
- if(w1.count != w2.count)
- return Integer.compare(w2.count, w1.count);
- else if(w1.featureRequestIds.size() != w2.featureRequestIds.size())
- return Integer.compare(w2.featureRequestIds.size(), w1.featureRequestIds.size());
- else
- return w1.word.compareTo(w2.word);
- }
- });
- pq.addAll(wordsMap.values());
- if(topFeatures > pq.size()) {
- for (int i = 0; i < numFeatures && !pq.isEmpty(); i++)
- res.add(pq.poll().word);
- } else {
- for(int i = 0; i < pq.size(); i++) {
- res.add(pq.poll().word);
- }
- }
- return res;
- }
- private static class Word {
- String word;
- int count;
- Set<Integer> featureRequestIds;
- public Word(String word, int count) {
- this.word = word;
- this.count = count;
- this.featureRequestIds = new HashSet<>();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment