-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMap.java
More file actions
84 lines (67 loc) · 2.12 KB
/
Map.java
File metadata and controls
84 lines (67 loc) · 2.12 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
import java.io.BufferedReader;
import java.io.FileReader;
public class Map {
public City[] cities;
private final int mod = 541;
public Map(String file) {
cities = new City[mod];
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
String[] row = line.split(",");
City city1 = lookup(row[0]);
City city2 = lookup(row[1]);
Integer distance = Integer.parseInt(row[2]);
city1.addConnection(city2, distance);
city2.addConnection(city1, distance);
hashadd(city1);
hashadd(city2);
}
} catch (Exception e) {
System.out.println(e);
}
}
private Integer hash(String name) {
int hash = 7;
for (int i = 0; i < name.length(); i++) {
hash = (hash * 31 % mod) + name.charAt(i);
}
return hash % mod;
}
// takes cityname. returns city if found in list. otherwise creates new city and
// returns that.
public City lookup(String cityName) {
int i = hash(cityName);
if (cities[i] != null && cities[i].cityName.equals(cityName)) {
return cities[i];
} else {
while (cities[i] != null) {
if (cities[i].cityName.equals(cityName)) {
return cities[i];
}
i++;
}
City newCity = new City(cityName);
return newCity;
}
}
private void hashadd(City input) {
int i = hash(input.cityName);
if (cities[i] == null) {
cities[i] = input;
} else if (cities[i] == input) {
return;
} else {
while (cities[i] != null) {
i++;
if (cities[i] == null) {
cities[i] = input;
return;
} else if (cities[i] == input) {
return;
}
}
cities[i] = input;
}
}
}