Skip to content

Instantly share code, notes, and snippets.

@benneuman
Created February 14, 2014 03:46
Show Gist options
  • Save benneuman/8995426 to your computer and use it in GitHub Desktop.
Save benneuman/8995426 to your computer and use it in GitHub Desktop.
def assert(actual, expected)
if actual == expected
puts "#{actual.inspect} equals #{expected.inspect}"
else
raise "Expected #{actual.inspect} to equal #{expected.inspect}"
end
end
LIVE = 'X'
DEAD = 'O'
def live_neighbor_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
def evolve(board)
board.map.with_index do |row, row_index|
row.map.with_index do |point, col_index|
neighbor_count = live_neighbor_count(row_index, col_index, board)
if point == LIVE
neighbor_count == 2 || neighbor_count == 3 ? LIVE : DEAD
else
neighbor_count == 3 ? LIVE : DEAD
end
end
end
end
#Testing dead cell with no neighbors stays dead
board = [%w(O)]
assert(evolve(board), [%w(O)])
#Testing live cell with no neighbors dies
board = [%w(X)]
assert(evolve(board), [%w(O)])
#Testing live cell with one neighbor dies
board = [%w(O X)]
assert(evolve(board), [%w(O O)])
#Testing live cell with two neighbors stays alive
board = [%w(X X X)]
assert(evolve(board), [%w(O X O)])
#Testing live cell with three neighbors stays alive
board = [%w(X X), %w(X X)]
assert(evolve(board), [%w(X X), %w(X X)])
#Testing live cell with more than three neighbors dies
# X O O
# X X X
# X O X
board = [%w(X O O), %w(X X X), %w(X O X)]
assert(evolve(board), [%w(X O O), %w(X O X), %w(X O X)])
#Testing dead cell with exactly three live neighbors comes alive
# X X
# X O
board = [%w(X X), %w(X O)]
assert(evolve(board), [%w(X X), %w(X X)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment