Skip to content

Instantly share code, notes, and snippets.

@thergbway
Created September 28, 2017 13:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thergbway/279d2e0df551c4af88724782c75c983b to your computer and use it in GitHub Desktop.
Save thergbway/279d2e0df551c4af88724782c75c983b to your computer and use it in GitHub Desktop.
[EXERCISE] Trie traversing (https://en.wikipedia.org/wiki/Trie)
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
//[mama, maman, abama]
//
//a b a m
//b m a a
//z k n m
//b d q q
class Field {
public static void main(String[] args) {
Node trie = createTrie(Arrays.asList("mama", "maman", "obama"));
char[][] field = {
{'a', 'b', 'a', 'm'},
{'b', 'm', 'a', 'a'},
{'z', 'k', 'n', 'm'},
{'b', 'd', 'q', 'q'}
};
for (int i = 0; i < field.length; ++i) {
for (int j = 0; j < field[0].length; ++j) {
if (hasWord(new boolean[field.length][field[0].length], field, i, j, trie)) {
System.out.println("Found word start: " + i + " " + j);
}
}
}
}
private static boolean hasWord(boolean[][] prohibited, char[][] field, int i, int j, Node root) {
throw new UnsupportedOperationException("Not finished yet");
}
private static Node createTrie(List<String> words) {
Node root = new Node();
fillNode(root, words, -1);
return root;
}
private static void fillNode(Node node, List<String> words, int idx) {
if (idx == -1) {//words does not have the same prefix
Map<Character, List<String>> map = words.stream().collect(Collectors.groupingBy(w -> w.charAt(0), Collectors.toList()));
for (Map.Entry<Character, List<String>> entry : map.entrySet()) {
Node curr = new Node();
curr.letter = entry.getKey();
node.next.put(entry.getKey(), curr);
fillNode(curr, entry.getValue(), 1);
}
} else {
for (String w : words) {
if (w.length() - 1 < idx) {
node.isTerminal = true;
}
}
Map<Character, List<String>> map = words.stream().filter((w) -> w.length() - 1 >= idx).collect(Collectors.groupingBy(w -> w.charAt(idx), Collectors.toList()));
for (Map.Entry<Character, List<String>> entry : map.entrySet()) {
Node curr = new Node();
curr.letter = entry.getKey();
node.next.put(entry.getKey(), curr);
fillNode(curr, entry.getValue(), idx + 1);
}
}
}
}
class Node {
public char letter = 0;
public boolean isTerminal = false;
public Map<Character, Node> next = new HashMap<>();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment