Last active
August 29, 2015 14:06
-
-
Save mascip/fc50c5da834f2f634349 to your computer and use it in GitHub Desktop.
Hobbit violence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; 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))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
positions is part of clojure-contrib, yes?