Created
May 7, 2016 18:26
-
-
Save aniruddha84/aa432fef4e1db4ee85953cc0ce78c093 to your computer and use it in GitHub Desktop.
Conway's Game of life
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# @param {Integer[][]} board | |
# @return {Void} Do not return anything, modify board in-place instead. | |
def game_of_life(board) | |
m = board.size | |
n = board[0].size | |
meta_data = {} | |
(0...m).each do |row| | |
(0...n).each do |col| | |
living_neighbours = live_neighbours(board, row, col) | |
# meta-data format -> [row:col] => [old_value, num_of_live_neighbours] | |
meta_data["#{row}:#{col}"] = [board[row][col], living_neighbours] | |
end | |
end | |
(0...m).each do |row| | |
(0...n).each do |col| | |
meta = meta_data["#{row}:#{col}"] | |
if meta[0].zero? # dead | |
board[row][col] = 1 if meta[1] == 3 | |
else | |
board[row][col] = ([2, 3].include?(meta[1]) ? 1 : 0) | |
end | |
end | |
end | |
end | |
def live_neighbours(board, row, col) | |
result = 0 | |
result += 1 if cell_exists?(board, row, col - 1) && board[row][col - 1] == 1 | |
result += 1 if cell_exists?(board, row - 1, col-1) && board[row - 1][col - 1] == 1 | |
result += 1 if cell_exists?(board, row-1, col) && board[row - 1][col] == 1 | |
result += 1 if cell_exists?(board, row-1, col+1) && board[row - 1][col + 1] == 1 | |
result += 1 if cell_exists?(board, row, col+1) && board[row][col + 1] == 1 | |
result += 1 if cell_exists?(board, row+1, col+1) && board[row + 1][col + 1] == 1 | |
result += 1 if cell_exists?(board, row+1, col) && board[row + 1][col] == 1 | |
result += 1 if cell_exists?(board, row+1, col-1) && board[row + 1][col - 1] == 1 | |
result | |
end | |
def cell_exists?(board, row, col) | |
return false if row >= board.size || row < 0 | |
return false if col >= board[0].size || col < 0 | |
true | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment