Class: LabyrinthSolver::Solver

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/subparry_labyrinth_solver/solver.rb

Overview

Takes a labyrinth and attempts to solve it saving the path taken

Constant Summary collapse

OPPOSITE_DIRECTIONS =
{ up: :down, right: :left, down: :up, left: :right }.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(labyrinth) ⇒ Solver

Returns a new instance of Solver.

Raises:

  • (ArgumentError)


15
16
17
18
19
20
# File 'lib/subparry_labyrinth_solver/solver.rb', line 15

def initialize labyrinth
  raise ArgumentError unless labyrinth.instance_of? Labyrinth

  @labyrinth = labyrinth
  @path = []
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



7
8
9
# File 'lib/subparry_labyrinth_solver/solver.rb', line 7

def path
  @path
end

Instance Method Details

#go_nextObject



22
23
24
25
26
27
28
# File 'lib/subparry_labyrinth_solver/solver.rb', line 22

def go_next
  next_dir = OPPOSITE_DIRECTIONS.find { |dir, opp| @labyrinth.open?(dir) && opp != @path.last }
  return dead_end unless next_dir

  go(next_dir.first)
  @path.push(next_dir.first)
end

#solveObject



30
31
32
# File 'lib/subparry_labyrinth_solver/solver.rb', line 30

def solve
  go_next until cheese?
end