comparison distances.rb @ 0:1eef88068f9f tip

initial commit of maze game source
author ferencd
date Sun, 15 Sep 2019 11:46:47 +0200
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:1eef88068f9f
1 #---
2 # Excerpted from "Mazes for Programmers",
3 # published by The Pragmatic Bookshelf.
4 # Copyrights apply to this code. It may not be used to create training material,
5 # courses, books, articles, and the like. Contact us if you are in doubt.
6 # We make no guarantees that this code is fit for any purpose.
7 # Visit http://www.pragmaticprogrammer.com/titles/jbmaze for more book information.
8 #---
9 class Distances
10 def initialize(root)
11 @root = root
12 @cells = {}
13 @cells[@root] = 0
14 end
15
16 def [](cell)
17 @cells[cell]
18 end
19
20 def []=(cell, distance)
21 @cells[cell] = distance
22 end
23
24 def cells
25 @cells.keys
26 end
27
28 def path_to(goal)
29 current = goal
30
31 breadcrumbs = Distances.new(@root)
32 breadcrumbs[current] = @cells[current]
33
34 until current == @root
35 current.links.each do |neighbor|
36 if @cells[neighbor] < @cells[current]
37 breadcrumbs[neighbor] = @cells[neighbor]
38 current = neighbor
39 break
40 end
41 end
42 end
43
44 breadcrumbs
45 end
46
47 def max
48 max_distance = 0
49 max_cell = @root
50
51 @cells.each do |cell, distance|
52 if distance > max_distance
53 max_cell = cell
54 max_distance = distance
55 end
56 end
57
58 [max_cell, max_distance]
59 end
60 end