Skip to content

Commit 738f9ca

Browse files
author
Leon Rische
committed
code for chapter 7 in ruby
1 parent da6478b commit 738f9ca

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# the graph
2+
graph = {}
3+
graph["start"] = {}
4+
graph["start"]["a"] = 6
5+
graph["start"]["b"] = 2
6+
7+
graph["a"] = {}
8+
graph["a"]["fin"] = 1
9+
10+
graph["b"] = {}
11+
graph["b"]["a"] = 3
12+
graph["b"]["fin"] = 5
13+
14+
graph["fin"] = {}
15+
16+
# the costs table
17+
costs = {}
18+
costs["a"] = 6
19+
costs["b"] = 2
20+
costs["fin"] = Float::INFINITY
21+
22+
# the parents table
23+
parents = {}
24+
parents["a"] = "start"
25+
parents["b"] = "start"
26+
parents["fin"] = nil
27+
28+
@processed = []
29+
30+
def find_lowest_cost_node(costs)
31+
lowest_cost = Float::INFINITY
32+
lowest_cost_node = nil
33+
# Go through each node.
34+
costs.each do |node, cost|
35+
# If it's the lowest cost so far and hasn't been processed yet...
36+
if cost < lowest_cost && !@processed.member?(node)
37+
# ... set it as the new lowest-cost node.
38+
lowest_cost = cost
39+
lowest_cost_node = node
40+
end
41+
end
42+
lowest_cost_node
43+
end
44+
45+
# Find the lowest-cost node that you haven't processed yet.
46+
node = find_lowest_cost_node(costs)
47+
# If you've processed all the nodes, this while loop is done.
48+
until node.nil?
49+
cost = costs[node]
50+
# Go through all the neighbors of this node.
51+
neighbors = graph[node]
52+
neighbors.keys.each do |n|
53+
new_cost = cost + neighbors[n]
54+
# If it's cheaper to get to this neighbor by going through this node...
55+
if costs[n] > new_cost
56+
# ... update the cost for this node.
57+
costs[n] = new_cost
58+
# This node becomes the new parent for this neighbor.
59+
parents[n] = node
60+
end
61+
end
62+
# Mark the node as processed.
63+
@processed << node
64+
# Find the next node to process, and loop.
65+
node = find_lowest_cost_node(costs)
66+
end
67+
68+
puts "Cost from the start to each node:"
69+
puts costs

0 commit comments

Comments
 (0)