Skip to content

Commit

Permalink
Import source
Browse files Browse the repository at this point in the history
  • Loading branch information
ewilderj committed Dec 19, 2011
1 parent ed2219c commit 194a2f1
Show file tree
Hide file tree
Showing 3 changed files with 89 additions and 0 deletions.
33 changes: 33 additions & 0 deletions simple/README
@@ -0,0 +1,33 @@
*Simple coin tosser*

Simulate the results of a coin toss experiment.

eg. (chart-scores (sample-scores 200 20)) will yield:

-13
-12 *
-11
-10 *******
-9
-8 *******
-7
-6 *****************
-5
-4 *******************
-3
-2 *************************
-1
0 *********************************
1
2 ******************************
3
4 *****************************
5
6 *******************
7
8 ***********
9
10 **
11
12
13
3 changes: 3 additions & 0 deletions simple/project.clj
@@ -0,0 +1,3 @@
(defproject coins "1.0.0"
:description "coin tossing"
:dev-dependencies [])
53 changes: 53 additions & 0 deletions simple/src/coins.clj
@@ -0,0 +1,53 @@
(use '[clojure.string :only (join)])

(defn coin-toss
"Tosses a fair coin and returns true for heads, false for tails"
[]
(= 1 (rand-int 2)))

(defn toss-score
"Win $1 for heads, lose $1 for tails"
[toss]
(if toss 1 -1))

(defn count-winnings
"Figure out the net result for a sequence of tosses"
[results]
(reduce + (map toss-score results)))

(defn sample-score
"Run an experiment of n tosses and figure out the result"
[n]
(count-winnings (repeatedly n coin-toss)))

(defn sample-scores
"Run a sequence of experiments n times with m tosses"
[n m]
(repeatedly n #(sample-score m)))

(defn tally-scores
"Return a map of frequency of results"
[scores]
(let
;; define an auxiliary function that registers a
;; score into a map holding all the score tallies
[tally-score (fn [results score]
(if-let [prev-count (results score)]
(assoc results score (inc prev-count))
(assoc results score 1)))]
(reduce tally-score {} scores)))

(defn chart-scores
"Given a list of scores, print a simple ASCII frequency graph"
[scores]
(let [tally (tally-scores scores)
low (apply min (keys tally))
high (apply max (keys tally))
r (inc (max (Math/abs low) high))]
(doseq [val (range (- r) (inc r))]
(print val)
(print "\t")
(if-let [c (tally val)]
(print (join (repeat c "*"))))
(println)
)))

0 comments on commit 194a2f1

Please sign in to comment.