Game of Life

Here’s a medium problem of which I found out a weird behavior, probably a bug in LeetCode.

class Solution {
    
    private val getNeighborCount:(Array<IntArray>, Int, Int) -> Int = { dup, row, column ->
        var liveNeighbors = 0
        (-1..1).forEach { x ->
            (-1..1).forEach { y ->
                val horiz = row + x
                val vert = column + y
                
                if(horiz >= 0 && horiz < dup.size && vert >= 0 && vert < dup.first().size){
                    liveNeighbors += if(dup[horiz][vert] == 1) 1 else 0
                }
            }    
        }
        
        liveNeighbors + if(dup[row][column] == 1) -1 else 0
    }
    
    fun gameOfLife(board: Array<IntArray>): Unit {
        val dup = Array<IntArray>(board.size) { IntArray(board.first().size)}
        (0 until board.size).forEach { row ->
            (0 until board.first().size).forEach { column ->
                dup[row][column] = board[row][column]
            }
        }
        
        (0 until board.size).forEach { row ->
            (0 until board.first().size).forEach { col->
                val nCount = getNeighborCount(dup, row, col)
                when{
                    nCount < 2 || nCount > 3 -> if(dup[row][col] == 1) {
                        board[row][col] = 0
                    }
                    nCount == 3 -> if(dup[row][col] == 0) {
                        board[row][col] = 1   
                    }
                }
            }            
        }
    }
}
Runtime: 196 ms, faster than 11.11% of Kotlin online submissions for Game of Life.
Memory Usage: 35.2 MB, less than 100.00% of Kotlin online submissions for Game of Life.

The first part of the code is just to create a copy of the array board. We can easily use board.clone() but this doesn’t seem to be working properly. My expectation is that, the cloned version shouldn’t be affected by changes done in board but it isn’t the case. So here, I had to manually copy the values to the dup array.

Then, the next part is just purely iteration and applying the rules for each and every cell.

comments powered by Disqus