-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringTree.java
More file actions
93 lines (84 loc) · 2.67 KB
/
StringTree.java
File metadata and controls
93 lines (84 loc) · 2.67 KB
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
87
88
89
90
91
92
93
import java.util.ArrayList;
public class StringTree {
private Cluster root;
private int numNodes = 0;
private ArrayList<String> found;
public StringTree() {
found = new ArrayList<String>();
}
public void storeString(String s) {
if (root == null) {
numNodes++;
root = new Cluster(numNodes, s, 0);
}
else {
insert(s, root);
}
}
public void insert(String s, Cluster c) {
int centerDiff = Difference.calcDiff(c.getCenter(), s);
int min = 1000;
int minIndex = 0;
for (int i = 0; i < c.getNumChildren(); i++) {
Cluster child = c.getChild(i);
int diff = Difference.calcDiff(s, child.getCenter());
if (diff < min) {
min = diff;
minIndex = i;
}
}
if (centerDiff < min)
c.insertString(s);
else
insert(s, c.getChild(minIndex));
}
/**
* Wrapper for main serach method
*
* @param s String to search for
* @param tolerance of difference
*/
public void search(String s, int tolerance) {
found.clear();
recursiveSearch(s, tolerance, root);
}
/**
* Checks to see if current cluster is within difference
* range -- search cluster if it is.
*
* Find child with smallest difference and recurse on
* that child
*
* @param s string to search for
* @param tolerance of difference
* @param c Cluster to search
*/
public void recursiveSearch(String s, int tolerance, Cluster c) {
int minDiff = 0;
//Find matches within current cluster
if (Difference.calcDiff(c.getCenter(), s) <= c.getRadius() + tolerance) {
ArrayList<String> strings = c.getStrings();
for (int i = 0; i < strings.size(); i++) {
if (Difference.calcDiff(strings.get(i), s) < tolerance)
found.add(strings.get(i));
}
}
//If at a leaf, return
if (c.getNumChildren() == 0)
return;
//Find child with smallest difference
int min = 10000;
int minIndex = 0;
for (int i = 0; i < c.getNumChildren(); i++) {
Cluster child = c.getChild(i);
int difference = Difference.calcDiff(child.getCenter(), s);
if (difference < min) {
min = difference;
minIndex = i;
}
}
//Recurse on child with smallest difference
recursiveSearch(s, tolerance, c.getChild(minIndex));
}
public ArrayList<String> getFound() { return found; }
}