|
| 1 | +# https://leetcode.com/problems/game-of-life/ |
| 2 | +# |
| 3 | +# According to the Wikipedia's article: "The Game of Life, also known simply |
| 4 | +# as Life, is a cellular automaton devised by the British mathematician John |
| 5 | +# Horton Conway in 1970." |
| 6 | +# |
| 7 | +# Given a board with m by n cells, each cell has an initial state live (1) |
| 8 | +# or dead (0). Each cell interacts with its eight neighbors (horizontal, |
| 9 | +# vertical, diagonal) using the following four rules (taken from the above |
| 10 | +# Wikipedia article): |
| 11 | +# |
| 12 | +# + Any live cell with fewer than two live neighbors dies, as if caused |
| 13 | +# by under-population. |
| 14 | +# + Any live cell with two or three live neighbors lives on to the next |
| 15 | +# generation. |
| 16 | +# + Any live cell with more than three live neighbors dies, as if by |
| 17 | +# over-population.. |
| 18 | +# + Any dead cell with exactly three live neighbors becomes a live cell, |
| 19 | +# as if by reproduction. |
| 20 | +# |
| 21 | +# Write a function to compute the next state (after one update) of the board |
| 22 | +# given its current state. |
| 23 | +# |
| 24 | +# Follow up: |
| 25 | +# |
| 26 | +# + Could you solve it in-place? Remember that the board needs to be |
| 27 | +# updated at the same time: You cannot update some cells first and |
| 28 | +# then use their updated values to update other cells. |
| 29 | +# + In this question, we represent the board using a 2D array. In |
| 30 | +# principle, the board is infinite, which would cause problems when |
| 31 | +# the active area encroaches the border of the array. How would you |
| 32 | +# address these problems? |
| 33 | + |
| 34 | + |
| 35 | +# @param {Integer[][]} board |
| 36 | +# @return {Void} Do not return anything, modify board in-place instead. |
| 37 | +def game_of_life(board) |
| 38 | + return if board.empty? |
| 39 | + |
| 40 | + m, n = board.size, board[0].size |
| 41 | + dx = [-1, -1, -1, 0, 0, 1, 1, 1] |
| 42 | + dy = [-1, 0, 1, -1, 1, -1, 0, 1] |
| 43 | + |
| 44 | + 0.upto(m - 1) do |x| |
| 45 | + 0.upto(n - 1) do |y| |
| 46 | + count = 0 |
| 47 | + |
| 48 | + 0.upto(7) do |idx| |
| 49 | + u, v = x + dx[idx], y + dy[idx] |
| 50 | + count += board[u][v] & 0b01 if u.between?(0, m - 1) && v.between?(0, n - 1) |
| 51 | + end |
| 52 | + |
| 53 | + if board[x][y] & 0b01 == 0b01 |
| 54 | + board[x][y] |= 0b10 if count == 3 || count == 2 |
| 55 | + else |
| 56 | + board[x][y] |= 0b10 if count == 3 |
| 57 | + end |
| 58 | + end |
| 59 | + end |
| 60 | + |
| 61 | + 0.upto(m - 1) do |x| |
| 62 | + 0.upto(n - 1) do |y| |
| 63 | + board[x][y] >>= 1 |
| 64 | + end |
| 65 | + end; nil |
| 66 | +end |
0 commit comments