1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
|
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FindAnagrams
{
// function to put data from a file into a list
static ArrayList<String> fileToList(String filename) throws IOException{
ArrayList<String> list = new ArrayList<String>();
FileReader f = new FileReader(filename);
BufferedReader BF = new BufferedReader(f);
while( BF.ready()){
String line = BF.readLine();
list.add(line);}
return list;
}
//str is a file name
static Map<String, List<String>> getAnagrams(String str) throws IOException {
Map<String, List<String>> map = new HashMap<String, List<String>>();
// get all the words. (or build the dictionary.)
ArrayList<String> words= fileToList(str);
for (String wd : words) {
if (wd.length() <= 1)
continue;
// sort the characters in this word
char[] chars = wd.toCharArray();
Arrays.sort(chars);
String anaKey = String.valueOf(chars) ;
// update anagrams list
List<String> anagramList = null;
if (map.containsKey(anaKey)) {
anagramList = map.get(anaKey);
}
if (anagramList == null) {
anagramList = new ArrayList<String>();
map.put(anaKey,anagramList);
}
if (!(anagramList).contains(wd)) {
(anagramList).add(wd);
}
}
// remove words without anagrams.
String keys[] = new String[map.size()];
for (String key : map.keySet().toArray(keys)) {
if (map.get(key).size() <= 1)
map.remove(key);
}
return map;
}
public static void main(String[] args) throws IOException {
Map<String, List<String>> lastmap=getAnagrams("wordlist.doc");
Collection<List<String>> lastmap1=lastmap.values();
for (List<String> lis : lastmap1){
for (String wd : lis){
System.out.print(wd + " ");
}
System.out.print("\n");
}
}
} |
Partager