Skip to content

Instantly share code, notes, and snippets.

@tnoda
Created May 17, 2012 08:15
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 tnoda/2717342 to your computer and use it in GitHub Desktop.
Save tnoda/2717342 to your computer and use it in GitHub Desktop.
Inverse Fizzbuzz solver in Clojure
;; Question: Inverse FizzBuzz (Clojure version) - Given a collection
;; whose elements are one of :fizz, :buzz, and :fizzbuzz, what's the
;; shortest contiguous sequence of numbers that produces that list when
;; you run fizzbuzz ?
;;
;; Originally introduced at:
;; http://www.jasq.org/2/post/2012/05/inverse-fizzbuzz.html
(ns tnoda.inverse-fizzbuzz.core
(:use [clojure.test :only [deftest are]]))
(defn- fizzbuzz [n]
(cond (zero? (mod n 15)) :fizzbuzz
(zero? (mod n 3)) :fizz
(zero? (mod n 5)) :buzz))
(defn- fizzbuzz-seq [length]
(comp (juxt (partial map first) (partial map second))
(partial take length)
(partial filter first)
(partial map (juxt fizzbuzz identity))
(partial iterate inc)
inc))
(defn- triple [coll]
(comp (partial cons coll)
(fizzbuzz-seq (count coll))))
(defn- triples [coll]
(map (triple coll) [0 3 5 6 9 10 12]))
(defn- match? [[expected actual _]]
(= expected actual))
(defn- actual-length [s]
(- (last (last s)) (first (last s))))
(def solve
(comp (juxt first last)
last
first
(partial sort-by actual-length)
(partial filter match?)
triples))
(deftest test-solve
(are [x y] (= (solve x) y)
[:fizz] [3 3]
[:fizz :buzz] [9 10]
[:buzz :fizz :fizz] [5 9]
[:fizz :fizz :buzz] [6 10]
[:fizzbuzz :fizz] [15 18]
[:fizzbuzz :fizzbuzz] [nil nil]
[:fizz :buzz :fizz :fizz :buzz] [3 10]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment