Class: Amaze::Distances

Inherits:
Object
  • Object
show all
Defined in:
lib/amaze/distances.rb

Instance Method Summary collapse

Constructor Details

#initialize(root) ⇒ Distances

Returns a new instance of Distances.



4
5
6
7
8
# File 'lib/amaze/distances.rb', line 4

def initialize root
  @root = root
  @cells = {}
  @cells[root] = 0
end

Instance Method Details

#[](cell) ⇒ Object



10
11
12
# File 'lib/amaze/distances.rb', line 10

def [] cell
  @cells[cell]
end

#[]=(cell, distance) ⇒ Object



14
15
16
# File 'lib/amaze/distances.rb', line 14

def []= cell, distance
  @cells[cell] = distance
end

#cellsObject



18
19
20
# File 'lib/amaze/distances.rb', line 18

def cells
  @cells.keys
end

#maxObject



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/amaze/distances.rb', line 40

def max
  max_cell = @root
  max_distance = 0
  
  @cells.each do |cell, distance|
    if distance > max_distance
      max_cell = cell
      max_distance = distance
    end
  end
  
  [max_cell, max_distance]
end

#path_to(goal) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/amaze/distances.rb', line 22

def path_to goal
  current = goal
  breadcrumbs = Amaze::Distances.new @root
  breadcrumbs[current] = @cells[current]
  
  until current == @root
    current.links.each do |neighbor|
      if @cells[neighbor] < @cells[current]
        breadcrumbs[neighbor] = @cells[neighbor]
        current = neighbor
        break
      end 
    end
  end
  
  breadcrumbs
end