Re: find words that contains some specific letters
In article
<b6695e89-1b15-47fc-b99a-4db293706177@v2g2000vbb.googlegroups.com>,
Lew <lew@lewscanon.com> wrote:
[...]
With a HashMap<String, Set<String>> approach, the entire Set of
resultant dictionary words is indexed by the search string, so one
simple 'dictionary.get( searchTerm )' yields an entire result set
directly.
Implementing <http://en.wikipedia.org/wiki/Jumble>, your HashMap<String,
Set<String>> makes an excellent dictionary. The Map takes a little extra
time to construct, but the result is static. Once the characters of an
input word are sorted, O(n log n), the lookup is indeed O(1).
So I remain puzzled, and still need the answer.
<code>
package org.gcs.jumble;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
/**
* Jumble.
* @author John B. Matthews
*/
public class Jumble {
private static final String NAME = "/usr/share/dict/words";
private static final Map<String, Set<String>> map =
new HashMap<String, Set<String>>();
static {
try {
File file = new File(NAME);
BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream(file)));
String s;
while ((s = in.readLine()) != null) {
byte[] ba = s.getBytes();
Arrays.sort(ba);
String sorted = new String(ba);
Set words = map.get(sorted);
if (words == null) {
words = new TreeSet<String>();
words.add(s);
map.put(sorted, words);
} else {
words.add(s);
}
}
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
public static void main(String... args) {
if (args.length < 1) {
showHelp();
} else {
for (String word : args) {
System.out.println(word + ":");
byte[] ba = word.getBytes();
Arrays.sort(ba);
Set<String> words = map.get(new String(ba));
if (words != null) {
for (String s : words) {
System.out.println(s);
}
}
}
}
}
private static void showHelp() {
System.out.println(
"Usage: java -jar Jumble.jar <word> [<word>]");
}
}
</code>
--
John B. Matthews
trashgod at gmail dot com
<http://sites.google.com/site/drjohnbmatthews>