Skip to content

Instantly share code, notes, and snippets.

@mascip
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mascip/fc50c5da834f2f634349 to your computer and use it in GitHub Desktop.
Save mascip/fc50c5da834f2f634349 to your computer and use it in GitHub Desktop.
Hobbit violence
; Hobbit violence
; My version of this exercise,
; found at http://www.braveclojure.com/do-things/
(def a-body [
{:part "head", :size 3}
{:part "eye", :size 1, :symmetrical true}
{:part "ear", :size 1, :symmetrical true}
{:part "mouth", :size 1}
{:part "neck", :size 2}])
(defn symmetrize-part [body-part]
(if-not (:symmetrical body-part)
[body-part]
[(merge {:side "left"} body-part)
(merge {:side "right"} body-part)]))
(defn symmetrize-body [body]
(mapcat symmetrize-part body))
(defn hit-a-body-part [a-body]
(let [
sizes (map :size a-body)
total-body-size (reduce + sizes)
target (rand-int (+ 1 total-body-size))
accum-size (reductions + sizes)
; Touched where accum-size >= target
touched-part (nth a-body
(first (positions #(<= target %) accum-size)))]
touched-part))
(defn say-body-part [a-part]
(println (str
(when (:side a-part) (str (:side a-part) " "))
(:part a-part))))
(say-body-part (hit-a-body-part (symmetrize-body a-body)))
@jkwatson
Copy link

positions is part of clojure-contrib, yes?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment