-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdistance.rb
53 lines (45 loc) · 1.19 KB
/
distance.rb
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
# Calculates shortest distance in a graph by visiting all nodes.
# Permutes the order in which the nodes are visisted and takes
# the shortest path to the next node in the list, possibly revisiting
# older nodes.
class Distance
attr_reader :nodes, :adjacency
def initialize(nodes, adjacency)
@nodes = nodes
@adjacency = adjacency
end
# Calculates the distance between two points in a 2d cartesian system
def self.between(a, b)
dx = b['x'] - a['x']
dy = b['y'] - a['y']
Math.sqrt(dx**2 + dy**2)
end
# Get the nodes traversed by the shortest path
def shortest_path
distances.min_by(&:last).first
end
# Get the distance of the shortest path
def shortest_distance
distances.min_by(&:last).last
end
def to_s
distances.inspect
end
private
def distances
results = {}
valid_permutations.each do |permutation|
distance = 0
permutation.each_cons(2) do |from, to|
distance += adjacency.get(from, to)
end
results[permutation.join('-')] = distance
end
return results
end
def valid_permutations
nodes.permutation.select do |perm|
perm.first == nodes.first && perm.last == nodes.last
end
end
end