Create a gist now

Instantly share code, notes, and snippets.

@shrayasr /snl.clj
Last active Sep 14, 2015

What would you like to do?
Snakes and Ladders - Functional Conf 2015 - Code Jugalbandi challenge
(def snls {2 99 ; ladder
7 70 ; ladder
71 3 ; snake
50 5 ; snake
98 1 ; snake
})
(defn roll-dice []
(+ (rand-int 6) 1))
(def max-cell 100)
(defn next-turn-v2 [player-positions]
(loop [state player-positions
new-state []]
(if (empty? state)
new-state
(let [x (first state)
xs (rest state)
dice-roll (roll-dice)
x-new-pos (+ x dice-roll)
on-snl? (get snls x-new-pos nil)]
(if (> x-new-pos max-cell)
(recur xs (conj new-state x))
(do
(if on-snl?
(recur xs (conj new-state (get snls x-new-pos)))
(recur xs (conj new-state x-new-pos)))))))))
(defn next-turn [player-positions]
(map (fn [player-curr-pos] ; using map means 2 players can win at once
(let [dice-roll (roll-dice)
player-new-pos (+ player-curr-pos dice-roll)
on-snl? (get snls player-new-pos nil)]
(if (> player-new-pos max-cell)
player-curr-pos
(do
(if on-snl?
(get snls player-new-pos)
player-new-pos))))) player-positions))
(defn game [no-of-players]
(let [initial-state (vec (repeat no-of-players 1))]
(loop [state initial-state]
(let [next-state (next-turn-v2 state)
someone-has-won? (some #(>= % 100) next-state)]
(if someone-has-won?
next-state
(do
(println state)
(println next-state)
(recur next-state)))))))
# At the repl, to run the game use the `game` function with the no. of players as an argument
=> (game 10)
[1 1 1 1 1 1 1 1 1 1]
[99 4 3 70 6 3 6 6 4 6]
[99 4 3 70 6 3 6 6 4 6]
[99 5 5 75 9 9 8 70 8 10]
[99 5 5 75 9 9 8 70 8 10]
[99 8 70 77 15 10 14 3 11 11]
[99 8 70 77 15 10 14 3 11 11]
[99 14 75 80 16 16 15 70 17 13]
[99 14 75 80 16 16 15 70 17 13]
[99 17 76 84 20 20 16 76 18 18]
[99 17 76 84 20 20 16 76 18 18]
[99 23 78 87 22 23 22 81 24 24]
[99 23 78 87 22 23 22 81 24 24]
[99 24 79 92 26 25 23 83 30 27]
[99 24 79 92 26 25 23 83 30 27]
[99 26 82 95 31 30 26 88 31 30]
[99 26 82 95 31 30 26 88 31 30]
[99 27 86 96 36 35 32 93 36 36]
[99 27 86 96 36 35 32 93 36 36]
[99 30 88 97 41 36 36 1 37 37]
[99 30 88 97 41 36 36 1 37 37]
[99 33 94 97 44 42 40 3 40 41]
[99 33 94 97 44 42 40 3 40 41]
[99 36 96 1 5 47 41 70 43 46]
[99 36 96 1 5 47 41 70 43 46]
[99 37 97 70 8 52 42 76 46 47]
[99 37 97 70 8 52 42 76 46 47]
[99 43 97 75 13 57 47 80 48 48]
[100 48 1 80 15 63 51 85 54 53]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment