Created
December 9, 2014 19:00
-
-
Save maksadbek/7d0e709e4e3913263259 to your computer and use it in GitHub Desktop.
anagram
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.*; | |
import java.io.*; | |
public class Anagrams { | |
public static void main(String[] args) { | |
int minGroupSize = Integer.parseInt(args[1]); | |
// Read words from file and put into a simulated multimap | |
Map<String, List<String>> m = new HashMap<String, List<String>>(); | |
try { | |
Scanner s = new Scanner(new File(args[0])); | |
while (s.hasNext()) { | |
String word = s.next(); | |
String alpha = alphabetize(word); | |
List<String> l = m.get(alpha); | |
if (l == null) | |
m.put(alpha, l=new ArrayList<String>()); | |
l.add(word); | |
} | |
} catch (IOException e) { | |
System.err.println(e); | |
System.exit(1); | |
} | |
// Print all permutation groups above size threshold | |
for (List<String> l : m.values()) | |
if (l.size() >= minGroupSize) | |
System.out.println(l.size() + ": " + l); | |
} | |
private static String alphabetize(String s) { | |
char[] a = s.toCharArray(); | |
Arrays.sort(a); | |
return new String(a); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment