forked from destiny1020/algorithm_playground
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSymbolGraph.java
More file actions
88 lines (73 loc) · 1.62 KB
/
SymbolGraph.java
File metadata and controls
88 lines (73 loc) · 1.62 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
package chap4;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import chap3.ST;
public class SymbolGraph
{
private ST<String, Integer> st;
private String[] names;
private Graph g;
public SymbolGraph(String filePath, String delimiter) throws IOException
{
// Init ST
st = new ST<String, Integer>();
// Init split
String split = (delimiter == null || delimiter.isEmpty()) ? "\\s"
: delimiter;
String[] parts;
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line = reader.readLine();
while (null != line && !line.isEmpty())
{
parts = line.split(split);
for (int i = 0; i < parts.length; i++)
{
if (!st.contains(parts[i]))
{
st.put(parts[i], st.size());
}
}
line = reader.readLine();
}
// Init the inverse index, index => key
names = new String[st.size()];
for (String key : st.keys())
{
names[st.get(key)] = key;
}
// Init the underlying graph
g = new Graph(st.size());
reader = new BufferedReader(new FileReader(filePath));
line = reader.readLine();
while (null != line && !line.isEmpty())
{
parts = line.split(split);
int start = st.get(parts[0]);
for (int i = 1; i < parts.length; i++)
{
int end = st.get(parts[i]);
g.addEdge(start, end);
}
line = reader.readLine();
}
reader.close();
}
public boolean contains(String key)
{
return st.contains(key);
}
public int index(String key)
{
Integer index = st.get(key);
return (index == null) ? -1 : index;
}
public String name(int index)
{
return names[index];
}
public Graph g()
{
return g;
}
}