Skip to content

Instantly share code, notes, and snippets.

@eggsyntax
Created June 13, 2016 01:22
Show Gist options
  • Save eggsyntax/b5dd2f7914c600a41ddf0e254eac7dab to your computer and use it in GitHub Desktop.
Save eggsyntax/b5dd2f7914c600a41ddf0e254eac7dab to your computer and use it in GitHub Desktop.
;; Declare namespace
(ns harmonium.sock-problem2
(:require [clojure.pprint :refer [pprint]]))
;; ============ Starting here are some functions ===========
;; ============ for formatting output; feel free ===========
;; ============ to ignore. ===========
(defn to-percent [total n]
"Given a value n and a total, take n / total, cast to a %,
truncate to an integer, and return as a pretty string."
(str (int (* 100
(/ n total)))
"%"))
(defn transform-map
"Just a convenience function for when we convert to percentages.
Apply a function f to each value of a map, returning the
transformed map."
[m f]
(into {}
(for [[k v] m]
[k (f v)])))
(defn freq-count-as-percents
"Given a frequency count like {:a 1, :b 2, :c 2}, will return
a modified frequency count like {:a 20, :b 40, :c 40}, where each
value is the percent value corresponding to that result"
[frequency-count]
(let [total-cases (apply + (vals frequency-count))
to-percent-with-total (partial to-percent total-cases)]
(transform-map frequency-count to-percent-with-total)))
(defn sort-alpha [m]
"Sort a map alphabetically by key"
(into
(sorted-map-by #(compare (str %1) (str %2)))
m))
;; ============ ===========
;; ============ End formatting functions ===========
;; ============ ===========
;; 20% of the time, we assign the socks to :not-in-dresser. The
;; other 80% of the time, we pick a random drawer and assign the
;; socks to it.
(defn create-location-list [num-samples]
(for [i (range num-samples)]
;; 20% of the time, assign to :not-in-dresser
(if (< (rand) 0.2)
:not-in-dresser
;; the other 80% of the time, pick a random drawer and
;; put the socks in it
(+ 1 (rand-int 8)))))
(def first-six-drawers #{1 2 3 4 5 6})
(defn drop-cases-where-first-six-drawers [rand-drawers]
(remove first-six-drawers rand-drawers))
;; Note that the built-in function "frequencies" builds a
;; frequency count (ie a histogram) from a list. For example:
;; >>> (frequencies [:a :a :b :c :b :d])
;; {:a 2, :b 2, :c 1, :d 1}
;; Here's the whole pipeline. You could comment out the last n
;; lines of it if you want to see the results at any of the
;; intermediate stages.
(def num-samples 100000)
(pprint
(-> (create-location-list num-samples)
drop-cases-where-first-six-drawers
frequencies
freq-count-as-percents
sort-alpha
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment