Skip to content

Instantly share code, notes, and snippets.

@hyone
Created May 20, 2012 05:31
Show Gist options
  • Save hyone/2751567 to your computer and use it in GitHub Desktop.
Save hyone/2751567 to your computer and use it in GitHub Desktop.
Inverse FizzBuzz by Clojure #2
;; Inverse Fizzbuzz - just another scala quant - http://www.jasq.org/2/post/2012/05/inverse-fizzbuzz.html
(ns inverse-fizzbuzz.core
(:use [clojure.test :only (deftest are)]))
(defn unzip [coll]
(if-not (empty? coll)
(apply map list coll)))
(defn fizzbuzz []
(map #(cond (zero? (mod % 15)) :fizzbuzz
(zero? (mod % 3)) :fizz
(zero? (mod % 5)) :buzz
:else nil)
(drop 1 (range))))
(defn fizzbuzz-indexed []
(filter identity
(map #(if %1 [%2 %1]) (fizzbuzz) (drop 1 (range)))))
(defn inverse-fizzbuzz [words]
(keep (fn [[indexes parts]]
(if (= words parts) ((juxt first last) indexes)))
(take-while #(<= (ffirst %) 15)
(map unzip (partition (count words) 1 (fizzbuzz-indexed))))))
(defn solve [words]
(first (sort-by (fn [[s e]] (- e s)) (inverse-fizzbuzz words))))
(deftest test-solve
(are [x y] (= (solve x) y)
[:fizz] [3 3]
[:buzz] [5 5]
[:fizz :buzz] [9 10]
[:buzz :fizz] [5 6]
[:fizz :buzz :fizz] [3 6]
[:fizz :fizz] [6 9]
[:fizz :fizz :buzz] [6 10]
;; additional check
[:fizzbuzz :fizz] [15 18]
[:fizzbuzz :fizzbuzz] nil))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment