-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConversion.java
More file actions
85 lines (77 loc) · 3.04 KB
/
Copy pathConversion.java
File metadata and controls
85 lines (77 loc) · 3.04 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
import java.util.*;
import java.util.HashMap;
public class Conversion {
public static void addRule(Map<String, Map<String, Double>> rules, String source, String destination, double conversion) {
if (!rules.containsKey(source)) {
Map<String, Double> neighbors = new HashMap<>();
rules.put(source, neighbors);
}
rules.get(source).put(destination, conversion);
System.out.println(rules);
}
public static double getRule(Map<String, Map<String, Double>> rules, String source, String destination) {
// source and destination must be in the rule set
if (!rules.containsKey(source) || !rules.containsKey(destination)) {
return 0;
}
// tracks vertices which have already been visited
Set<String> visited = new HashSet<>();
// tracks the relationship between current vertex and how we got here
Map<String, String> predecessor = new HashMap<>();
// queue of vertices to visit
Queue<String> vertexQueue = new LinkedList<>();
vertexQueue.add(source);
boolean found = false;
while (!found && !vertexQueue.isEmpty()) {
String vertex = vertexQueue.remove();
visited.add(vertex);
Map<String, Double> neighbors = rules.get(vertex);
for (String dest : neighbors.keySet()) {
if (dest.equals(destination)) {
found = true;
}
if (!visited.contains(dest)) {
visited.add(dest);
vertexQueue.add(dest);
predecessor.put(dest, vertex);
}
}
}
if (!found) {
return 0;
}
// take the predecessors to create the path from source to destination
// the stack will effectively reverse predecessors
boolean done = false;
String previous = destination;
Stack<String> path = new Stack<>();
path.add(destination);
while (!done) {
path.add(predecessor.get(previous));
previous = predecessor.get(previous);
done = (previous.equals(source));
}
// calculate
double factor = 1;
String start = path.pop();
while (!path.isEmpty()) {
String end = path.pop();
Map<String, Double> neighbors = rules.get(start);
System.out.println("New factor: " + start + " " + end);
factor *= neighbors.get(end);
start = end;
}
return factor;
}
public static void main(String[] args) {
Map<String, Map<String, Double>> rules = new HashMap<>();
addRule(rules, "feet", "inches", 12);
addRule(rules, "hours", "minutes", 60);
addRule(rules, "inches", "feet", 1.0/12.0);
addRule(rules, "minutes", "hours", 1.0/60);
addRule(rules, "yards", "feet", 3);
addRule(rules, "feet", "yards", 1.0/3);
double factor = getRule(rules, "yards", "inches" );
System.out.print(factor);
}
}