Skip to content

Instantly share code, notes, and snippets.

@gzmask
Last active August 29, 2015 14:07
Show Gist options
  • Save gzmask/f132f8ce6c66322a7cd6 to your computer and use it in GitHub Desktop.
Save gzmask/f132f8ce6c66322a7cd6 to your computer and use it in GitHub Desktop.
nim codewar
(ns nim)
(defn nim-sum [state]
(apply bit-xor state))
(defn next-move [[i k] state]
(cond
(<= (inc k) (nth state i)) [i (inc k)]
(and (< (inc i) (count state)) (not= (nth state (inc i)) 0)) [(inc i) 1]
(>= (inc i) (dec (count state))) nil
:else (next-move [(+ 2 i) 0] state)))
(defn choose-move
"Picks a move to play given a game-state ISeq"
[game-state]
(loop [[i k] (next-move [0 0] game-state)]
(if (or (= (nim-sum (assoc game-state i (- (nth game-state i) k))) 0)
(= (next-move [i k] game-state)
nil))
[i k]
(recur (next-move [i k] game-state)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment