Skip to content

Instantly share code, notes, and snippets.

@hellerve
Last active January 19, 2020 15:13
Show Gist options
  • Save hellerve/a08cd7ce3c183f8f481e9e75f3e6a8d8 to your computer and use it in GitHub Desktop.
Save hellerve/a08cd7ce3c183f8f481e9e75f3e6a8d8 to your computer and use it in GitHub Desktop.
Our solutions to the puzzles from the Clojure Berlin Meetup in January, in Carp
; as an introduction, we tried to do string capitalization by hand,
; using as many different interesting idioms as possible
(defn capitalize-char [c]
(if (Char.lower-case? c)
(=> c
(to-int)
(- 32)
(from-int))
c))
(defn capitalize [s]
(if (= (length s) 0)
@s
(let [f (String.head s)]
(fmt "%c%s" (capitalize-char f) &(String.tail s)))))
(load "git@github.com:hellerve/anima.carp@master")
(use Anima)
(def x 800)
(def y 800)
(defmodule Bool
(defn random []
(= 1 (Int.random-between 0 2)))
)
(defn setup [rend] (framerate 3))
(defn state []
(Array.repeat 80
&(fn [] (Array.repeat 80 &Bool.random))))
(defn count-neighbors [state i j]
(Array.reduce
&(fn [acc coords]
(+ acc
(let [x (+ i @(Pair.a coords))
y (+ j @(Pair.b coords))
inner (Maybe.from (Array.nth state y) [])]
(if (Maybe.from (Array.nth &inner x) false)
1
0))))
0
&[(Pair.init -1 -1)
(Pair.init -1 0)
(Pair.init 0 -1)
(Pair.init -1 1)
(Pair.init 1 -1)
(Pair.init 1 1)
(Pair.init 0 1)
(Pair.init 1 0)])
)
(defn step [state]
(do
(for [i 0 (Array.length &state)]
(let [row (Array.unsafe-nth &state i)]
(for [j 0 (Array.length row)]
(let [cell (Array.unsafe-nth row j)
neighbors (count-neighbors &state i j)]
(cond
(and @cell (and (/= neighbors 2) (/= neighbors 3))) (Array.aset! row j false)
(and (not @cell) (= neighbors 3)) (Array.aset! row j true)
())))))
state))
(defn draw [rend state]
(do
(background rend 200)
(color rend 20)
(for [i 0 (Array.length &state)]
(let [row (Array.unsafe-nth &state i)]
(for [j 0 (Array.length row)]
(let [cell (Array.unsafe-nth row j)]
(when @cell
(rect rend (* j 10) (* i 10) 10 10))))))
(step state)))
(defsketch "Game of life" x y setup draw state)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment