I have been given this assignment for school:
You have been given a puzzle consisting of a row of squares each containing an integer, like this:
6, 4, 1, 3, 3, 1, 4, 1, 1, 0
The bold number on the initial square is a marker that can move to other squares along the row. At each step in the puzzle, you may move the marker the number of squares indicated by the integer in the square it currently occupies. The marker may move either left or right along the row but may not move past either end. The goal of the puzzle is to move the marker to the 0 at the far end of the row.
The program checks the index you are currently on, and moves either left or right a number of squares based on the integer at that index in the array. It decides this based on the bounds of the array, if it can't move the required number of squares to the left it will move to the right, and vice versa. In this program, the first move has to be 6 to the right, since it cannot move 6 spaces left without going out of bounds. Then, it has to move 4 left since it cant move 4 right, and it goes on like that.
I have got this working, and printing the process is worth extra credit. I have it printing the process, but it is out of order.
here is my code:
def self.solvable(start, board)
return false if start>= board.length || start<0
return false if @@infinite[start] == -1
return true if board[start] == 0
@@infinite[start] = -1
if solvable(board[start] + start, board)
puts "Shifted right " + board[start].to_s + " spaces, from index " + start.to_s + " to index " + (board[start] + start).to_s
return true
else
puts "Shifted left " + board[start].to_s + " spaces, from index " + start.to_s + " to index " + (start - board[start]).to_s
end
return solvable(start - board[start], board)
end
print "Enter an array of numbers: "
input = gets.chomp!
board = input.each_char.map(&:to_i)
@@infinite = input.each_char.map(&:to_i)
puts solvable(0, board)
I do not understand how to make the code output in a more logical order, printing 6 spaces right, 4 spaces left, etc... instead of the current output, which is:
Shifted left 4 spaces, from index 6 to index 2
Shifted left 3 spaces, from index 3 to index 0
Shifted left 1 spaces, from index 2 to index 1
Shifted left 1 spaces, from index 5 to index 4
Shifted right 1 spaces, from index 8 to index 9
Shifted right 1 spaces, from index 7 to index 8
Shifted right 3 spaces, from index 4 to index 7
Shifted right 4 spaces, from index 1 to index 5
Shifted right 6 spaces, from index 0 to index 6