Skip to content

Instantly share code, notes, and snippets.

@benneuman
Created February 12, 2014 22:48
Show Gist options
  • Save benneuman/8966142 to your computer and use it in GitHub Desktop.
Save benneuman/8966142 to your computer and use it in GitHub Desktop.
def assert(actual, expected)
raise "Expected #{actual.inspect} to equal #{expected.inspect}" unless actual == expected
end
LIVE = 'X'
DEAD = 'O'
def evolve(board)
board.map.with_index do |row, x|
row.map.with_index do |p, y|
if p == LIVE
puts get_live_count(x, y, board)
([2,3].include?(get_live_count(x, y, board))) ? LIVE : DEAD
else
DEAD
end
end
end
end
def get_live_count(x, y, board)
neighbors = get_neighbors(x, y)
filter_neighbors(neighbors, board).count { |rindex, cindex| board[rindex][cindex] == LIVE }
end
def filter_neighbors(neighbors, board)
neighbors.select do |rindex, cindex|
rindex >= 0 && rindex < board.length && cindex >= 0 && cindex < board[rindex].length
end
end
def get_neighbors(x, y)
[
[x, (y+1)],
[x, (y-1)],
[(x-1), y],
[(x+1), y],
[(x+1), (y+1)],
[(x-1), (y-1)],
[(x+1), (y-1)],
[(x-1), (y+1)]
]
end
# Rule #1
assert(evolve([%w(X O), %w(O O)]), [%w(O O), %w(O O)])
assert(evolve([%w(O O), %w(O X)]), [%w(O O), %w(O O)])
assert(evolve([%w(O O O), %w(O X O), %w(O O O)]), [%w(O O O), %w(O O O), %w(O O O)])
# Rule 2
assert(evolve([%w(X X X)]), [%w(O X O)])
assert(evolve([%w(O X O), %w(O X O), %w(O X O)]), [%w(O O O), %w(O X O), %w(O O O)])
assert(evolve([%w(O X O), %w(O X X)]), [%w(O X O), %w(O X X)])
assert(evolve([%w(O X O), %w(X X O)]), [%w(O X O), %w(X X O)])
#Here ends pairing
assert(evolve([%w(X O X), %w(O X O), %w(X O O)]), [%w(O O O), %w(O X O), %w(O O O)])
#Rule 3
assert(evolve([%w(X O X), %w(O X O), %w(X O X)]), [%w(O O O), %w(O O O), %w(O O O)])
puts "Test passed."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment