This was a basic anagram problem. Take an input word, find all its permutations, then check a dictionary file to see what if any of those are real words.
My input data:
8
lasting
lameness
severer
lapse
alerting
medical
tasking
crates
My answer:
3 3 3 5 4 4 3 6
The code works slowly, as in, it took maybe a minute. Aside from any other criticism, I'm curious to the following:
Why are these two so different in speed? Casting as
String
was much faster:String current = (String) iter.next();
and
String current = iter.next().toString();
Is there a smarter way than looping through the dictionary every single time for every permutation of a word?
Is there a better data structure for the dictionary than an
ArrayList
? If so, why?
package com.secryption.CA127Anagrams;
import java.util.*;
import java.io.File;
/**
* Created by bmarkey on 11/26/15.
*/
public class Anagrams {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Scanner inFile;
System.out.println("Enter Data: ");
int testCases = Integer.parseInt(in.nextLine());
ArrayList<String> dictionary = new ArrayList<>();
try {
File file = new File("/home/me/words.txt");
inFile = new Scanner(file);
while (inFile.hasNextLine()) {
dictionary.add(inFile.nextLine());
}
inFile.close();
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < testCases; i++) {
int counter = 0;
String inputStr = in.nextLine();
Set<String> allCombos = getPermutations(inputStr);
Iterator iter = allCombos.iterator();
while (iter.hasNext()) {
String current = (String) iter.next();
// String current = iter.next().toString();
for( int j = 0; j < dictionary.size(); j++) {
if (current.equals(dictionary.get(j))) {
counter++;
}
}
}
System.out.print((counter - 1) + " ");
}
}
public static Set<String> getPermutations(String str) {
Set<String> permResult = new HashSet<String>();
if (str == null) {
return null;
} else if (str.length() == 0) {
permResult.add("");
return permResult;
}
char firstChar = str.charAt(0);
String rem = str.substring(1);
Set<String> words = getPermutations(rem);
for (String newString : words) {
for ( int i = 0; i <= newString.length(); i++) {
permResult.add(permCharAdd(newString, firstChar, i));
}
}
return permResult;
}
public static String permCharAdd(String str, char c, int j) {
String first = str.substring(0, j);
String last = str.substring(j);
return first + c + last;
}
}
readWords
,printPermutations
. If you run into performance problems, usingStringBuilder
will be a rather big improvement when generating strings. \$\endgroup\$