-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSymbolGraph.java
More file actions
71 lines (60 loc) · 1.99 KB
/
Copy pathSymbolGraph.java
File metadata and controls
71 lines (60 loc) · 1.99 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
/*
* Sample usage: java SymbolGraph routes.txt " "
* Sample usage: java SymbolGraph movies.txt "/"
*/
public class SymbolGraph {
private SeparateChainingST<String, Integer> st; // String -> index
private String[] keys; // index -> String
private Graph G; // the graph
public SymbolGraph(String stream, String sp){
st = new SeparateChainingST<>();
In in = new In(stream);
// First pass: builds the index by reading strings to associate
// each distinct string with an index.
while (in.hasNextLine()){
String[] a = in.readLine().split(sp);
for (int i=0; i<a.length; i++) {
if (!st.contains(a[i])) {
st.put(a[i], st.size());
}
}
}
// Inverted index to get keys in an array
keys = new String[st.size()];
for (String name : st.keys())
keys[st.get(name)] = name;
// Second pass: builds the graph by connecting the first vertex
// on each line to all the others.
G = new Graph(st.size());
in = new In(stream);
while (in.hasNextLine()){
String[] a = in.readLine().split(sp);
int v = st.get(a[0]);
for (int i=1; i<a.length; i++)
G.addEdge(v, st.get(a[i]));
}
}
public boolean contains(String s){
return st.contains(s);
}
public int index(String s){
return st.get(s);
}
public String name(int v){
return keys[v];
}
public Graph G(){
return G;
}
public static void main(String[] args){
String filename = args[0];
String delim = args[1];
SymbolGraph sg = new SymbolGraph(filename, delim);
Graph G = sg.G();
while (StdIn.hasNextLine()){
String source = StdIn.readLine();
for (int w : G.adj(sg.index(source)))
StdOut.println(" "+sg.name(w));
}
}
}