Last active
December 3, 2023 06:26
-
-
Save SumitJainUTD/d9ef6eec0fb9c3bac2237c3dfe5a41bb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class Concordance { | |
static class Word{ | |
String text; | |
int count; | |
public Word(String text, int count ){ | |
this.text = text; | |
this.count = count; | |
} | |
@Override | |
public String toString() { | |
return "[" + text + " -- " +count +"]"; | |
} | |
} | |
public static List<Word> calculate(String input, int n){ | |
List<Word> list = new ArrayList<>(); | |
if (input==null || input.trim()=="") | |
return list; | |
String [] words = input.split(" "); | |
HashMap<String, Integer> map = new HashMap<>(); | |
PriorityQueue<Word> pq = new PriorityQueue<>((o1, o2)->(o2.count-o1.count)); | |
for(int i=0; i<words.length; i++){ | |
String x = words[i].toLowerCase(); | |
int count = map.getOrDefault(x, 0); | |
map.put(x, count+1); | |
} | |
for(String key: map.keySet()){ | |
pq.offer(new Word(key, map.get(key))); | |
} | |
while(n>0){ | |
list.add(pq.remove()); | |
n--; | |
} | |
return list; | |
} | |
public static void main(String[] args) { | |
String text = "Lorem Ipsum is simply dummy text of the printing and" + | |
" typesetting industry. Lorem Ipsum has been the industry's" + | |
" standard dummy text ever since the 1500s"; | |
int n = 2; | |
System.out.println(text); | |
System.out.println(calculate(text, n)); | |
System.out.println(); | |
text = "There are many variations of passages of Lorem" + | |
" Ipsum available, but the majority have suffered" + | |
" alteration in some form by injected humour, or" + | |
" randomised words which don't look even slightly of believable form"; | |
n = 3; | |
System.out.println(text); | |
System.out.println(calculate(text, n)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment