The problem is to create a data structure, similar to a binary search tree that can list all possible moves a knight (in chess) can make on a 8x8 board. I came up with a single node class with the current location, a parent and 8 possible children which represent the 8 possible moves a knight can make.
class KnightNode
attr_accessor :location, :child_1, :child_2, :child_4, :child_5, :child_7, :child_8, :child_10, :child_11
def initialize(location = nil)
@location = location
@parent = nil
#8 possible children, label them as if they were hands on a clock
@child_1 = nil
@child_2 = nil
@child_4 = nil
@child_5 = nil
@child_7 = nil
@child_8 = nil
@child_10 = nil
@child_11 = nil
end
end
def generate_tree(location)
root = KnightNode.new(location)
move1 = [root.location[0] + 1,root.location[1] + 2]
move2 = [root.location[0] + 2,root.location[1] + 1]
move4 = [root.location[0] + 2,root.location[1] - 1]
move5 = [root.location[0] + 1,root.location[1] - 2]
move7 = [root.location[0] - 1,root.location[1] - 2]
move8 = [root.location[0] - 2,root.location[1] - 1]
move10 = [root.location[0] - 2,root.location[1] - 1]
move11 = [root.location[0] - 1,root.location[1] + 2]
move1[0] > 7 && move1[1] > 7 ? root.child_1 = nil : root.child_1 = generate_tree(move1)
move2[0] > 7 && move2[1] > 7 ? root.child_2 = nil : root.child_2 = generate_tree(move2)
move4[0] > 7 && move4[1] < 0 ? root.child_4 = nil : root.child_4 = generate_tree(move4)
move5[0] > 7 && move5[1] < 7 ? root.child_5 = nil : root.child_5 = generate_tree(move5)
move7[0] < 0 && move7[1] < 7 ? root.child_7 = nil : root.child_7 = generate_tree(move7)
move8[0] < 0 && move8[1] < 0 ? root.child_8 = nil : root.child_8 = generate_tree(move8)
move10[0] < 0 && move10[1] < 0 ? root.child_10 = nil : root.child_10 = generate_tree(move10)
move11[0] < 0 && move11[1] > 7 ? root.child_11 = nil : root.child_11 = generate_tree(move11)
return root
end
generate_tree([3,3])
When I run this code, I run into a SystemStackError. My guess is that my recursion is going through an infinite loop, however I do not see the problem. Thanks in advance!