Last active
August 29, 2015 14:07
-
-
Save gzmask/f132f8ce6c66322a7cd6 to your computer and use it in GitHub Desktop.
nim codewar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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