Skip to content

Instantly share code, notes, and snippets.

@jonelf jonelf/gist:2164553
Created Mar 22, 2012

Embed
What would you like to do?
Labouchère system simulation in Clojure
; A Clojure version of the Labouchère system simulation in
; CoffeeScript by Anders Löfgren that can be found at
; https://github.com/gnidde/gniddegit/blob/master/roulette.coffee
; Ruby version at https://gist.github.com/2127599
;
; I'm a complete beginner at Clojure so there's little to
; no chance that this code follows conventions and such.
; 2012-03-20 jonelf@gmail.com
(def table-zeros 1)
(def max-bet 24)
(def red-numbers #{1,3,5,7,9,12,14,16,18,19,21,23,25,27,30,32,34,36})
(def nr-of-zeros-hit 0)
(defrecord Player [stake_name current_betmin current_betmax current_earnings])
(defn current-bet [player]
(+ (:current_betmin player) (:current_betmax player)))
(defn decrease-earnings [player]
(- (:current_earnings player) (current-bet player)))
(defn calculate-earnings [result, player]
(let [
current_earnings (decrease-earnings player),
win (some #(= (:stake_name player) %) result),
new_earnings (if win (+ (* 2 (current-bet player)) current_earnings) current_earnings),
new_betmax (if win (inc (:current_betmax player)) (dec (:current_betmax player))),
new_betmin (if win (:current_betmin player) (inc (:current_betmin player)))]
(if (or (>= new_betmin new_betmax) (> (+ new_betmin new_betmax) max-bet))
(assoc player :current_earnings new_earnings :current_betmin 1 :current_betmax 4)
(assoc player :current_earnings new_earnings :current_betmin new_betmin :current_betmax new_betmax))))
(defn hit []
(- (rand-int (+ 36 table-zeros)) (dec table-zeros)))
(defn roll [players]
(let [current-hit (hit)]
(if (> current-hit 0)
(let [result #{
(if (contains? red-numbers current-hit) :red :black)
(if (< current-hit 19) :low :high)
(if (= (mod current-hit 2) 0) :even :odd)}]
(map #(calculate-earnings result %) players))
(do
(def nr-of-zeros-hit (inc nr-of-zeros-hit))
(map (fn [p] (assoc p :current_earnings (decrease-earnings p))) players)))))
(defn sum-earnings [players]
(reduce + (map (fn [p] (:current_earnings p)) players)))
; Let's roll some marbles
(let [players_init [
(Player. :red 1 4 0) (Player. :black 1 4 0)
(Player. :low 1 4 0) (Player. :high 1 4 0)
(Player. :even 1 4 0) (Player. :odd 1 4 0)]]
(loop [cnt 100000 players players_init]
(if (= (mod cnt 10000) 0)
(printf "%d : Total earnings: %d. Nr of zeros hit: %d\n" cnt (sum-earnings players) nr-of-zeros-hit))
(if (= cnt 0)
(printf "The end.\n")
(recur (dec cnt) (doall (roll players))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.