Skip to content

Instantly share code, notes, and snippets.

@pandwoter
Created October 13, 2020 12:36
Show Gist options
  • Save pandwoter/ac5eca45c54d430f857ff0eae4c04579 to your computer and use it in GitHub Desktop.
Save pandwoter/ac5eca45c54d430f857ff0eae4c04579 to your computer and use it in GitHub Desktop.
ANTS PROBLEM
class Ant
DIRECTIONS = [[1,0], [0,1], [-1,0], [0,-1]] # [0]:right, [1]:bottom, [2]:left, [3]:top
def in_border?
(0 <= @position_x && @position_x < @size_x) && (0 <= @position_y && @position_y < @size_y)
end
def initialize(size, turns, middle = size/2)
@matrix = Array.new(size) { Array.new(size, 'W') }
@size_x, @size_y = size, size
@position_x, @position_y = middle, middle
@direction = 0
@moves = 0
while @moves < turns && in_border?
@matrix.each.with_index do |row, idx|
p row
puts "\n" if idx == @size_x - 1
end
move
end
end
def move
@moves += 1
@direction = (@matrix[@position_x][@position_y] == 'W' ? @direction + 1 : @direction - 1) % 4
case @matrix[@position_x][@position_y]
when 'B'
@matrix[@position_x][@position_y] = 'W'
when 'W'
@matrix[@position_x][@position_y] = 'B'
end
@position_x += DIRECTIONS[@direction][0]
@position_y += DIRECTIONS[@direction][1]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment