Skip to content

Instantly share code, notes, and snippets.

@mkulak
Last active November 1, 2015 20:47
Show Gist options
  • Save mkulak/c3ebc2c8df8a0f312a3e to your computer and use it in GitHub Desktop.
Save mkulak/c3ebc2c8df8a0f312a3e to your computer and use it in GitHub Desktop.
Game of life in Clojure and Kotlin (http://www.4clojure.com/problem/94)
(defn solve [input]
(let [neighbours (fn [[y x]]
(filter #(not= % [y x]) (for [i (range -1 2) j (range -1 2)] [(+ y i) (+ x j)])))
isLive (fn [[y x]]
(and (>= y 0) (< y (count input)) (>= x 0) (< x (count (input y)))
(not= (nth (input y) x) \space)))
shouldLive (fn [p]
(let [liveNeighbours (count (filter isLive (neighbours p)))]
(or (= liveNeighbours 3) (and (isLive p) (= liveNeighbours 2)))))]
(map
(fn [i] (apply str (map #(if (shouldLive [i %]) \# \space) (range (count (input i))))))
(range (count input)))))
--I'm absolute beginner in Haskell. That's why this code is so unidiomatic and ugly
solve input = let
neighbours = filter (\p -> p /= [0, 0]) (concatMap (\i -> map (\j -> [i, j]) [-1..1]) [-1..1])
isLive y x = y >= 0 && y < length input && x >= 0 && x < length (input !! y) && input !! y !! x /= ' '
shouldLive y x = let
liveNeighbours = length (filter (\[i, j] -> isLive (y + i) (x + j)) neighbours)
in
liveNeighbours == 3 || (isLive y x) && liveNeighbours == 2
in
map (\i -> map (\j -> if (shouldLive i j) then '#' else ' ') [0..(length (input !! i)) - 1]) [0..(length input) - 1]
fun solve(input: List<String>): List<String> {
val neighbours = (-1..1).flatMap {i -> (-1..1).map {j -> Pair(i, j)}}.filter { it != Pair(0, 0) }
fun isLive(y: Int, x: Int) = y in input.indices && x in input[y].indices && input[y][x] != ' '
fun shouldLive(y: Int, x: Int): Boolean {
val liveNeighbours = neighbours.count { isLive(y + it.first, x + it.second) }
return liveNeighbours == 3 || isLive(y, x) && liveNeighbours == 2
}
return input.indices.map { i ->
input[i].indices.map { j ->
if (shouldLive(i, j)) '#' else ' '
}.joinToString("")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment