Class: KnightsTour::Knight
- Inherits:
-
Object
- Object
- KnightsTour::Knight
- Defined in:
- lib/knights_tour.rb
Constant Summary collapse
- LEGAL_STEPS =
as [x, y] pairs
[ [-2, 1], [-1, 2], [ 1, 2], [ 2, 1], [ 2, -1], [ 1, -2], [-1, -2], [-2, -1] ]
Instance Attribute Summary collapse
-
#board ⇒ Object
readonly
Returns the value of attribute board.
-
#current_position ⇒ Object
readonly
Returns the value of attribute current_position.
-
#steps_taken ⇒ Object
readonly
Returns the value of attribute steps_taken.
Instance Method Summary collapse
- #find_next_positions ⇒ Object
-
#initialize(board_size, start_at) ⇒ Knight
constructor
A new instance of Knight.
- #initialize_copy(other) ⇒ Object
- #traverse_to(new_position) ⇒ Object
- #traversed? ⇒ Boolean
Constructor Details
#initialize(board_size, start_at) ⇒ Knight
Returns a new instance of Knight.
76 77 78 79 80 |
# File 'lib/knights_tour.rb', line 76 def initialize(board_size, start_at) @board = Array.new(board_size[0]) { Array.new(board_size[1], 0) } @steps_taken = 0 traverse_to(start_at) end |
Instance Attribute Details
#board ⇒ Object (readonly)
Returns the value of attribute board.
74 75 76 |
# File 'lib/knights_tour.rb', line 74 def board @board end |
#current_position ⇒ Object (readonly)
Returns the value of attribute current_position.
74 75 76 |
# File 'lib/knights_tour.rb', line 74 def current_position @current_position end |
#steps_taken ⇒ Object (readonly)
Returns the value of attribute steps_taken.
74 75 76 |
# File 'lib/knights_tour.rb', line 74 def steps_taken @steps_taken end |
Instance Method Details
#find_next_positions ⇒ Object
99 100 101 |
# File 'lib/knights_tour.rb', line 99 def find_next_positions sort_by_warnsdorffs_heuristics(find_next_positions_at(@current_position)) end |
#initialize_copy(other) ⇒ Object
82 83 84 85 |
# File 'lib/knights_tour.rb', line 82 def initialize_copy(other) @board = Marshal.load(Marshal.dump(other.board)) @steps_taken = other.steps_taken end |
#traverse_to(new_position) ⇒ Object
92 93 94 95 96 97 |
# File 'lib/knights_tour.rb', line 92 def traverse_to(new_position) @steps_taken += 1 @current_position = new_position @board[@current_position[0]][@current_position[1]] = @steps_taken self end |
#traversed? ⇒ Boolean
87 88 89 90 |
# File 'lib/knights_tour.rb', line 87 def traversed? last_step = @board.size * @board[0].size @steps_taken == last_step end |