Skip to content

Instantly share code, notes, and snippets.

@felipebueno
Last active September 18, 2015 18:09
Show Gist options
  • Save felipebueno/80222ecb29fb11b04f5b to your computer and use it in GitHub Desktop.
Save felipebueno/80222ecb29fb11b04f5b to your computer and use it in GitHub Desktop.
;; Write a program that prints the numbers from 1 to 100. But for
;; multiples of three print “Fizz” instead of the number and for
;; the multiples of five print “Buzz”. For numbers which are multiples
;; of both three and five print “FizzBuzz”
;; BEGIN - first solution (not that pretty but, hey, it works :P)
(defn- multiple-of-three [n]
(= 0 (mod n 3)))
(defn- multiple-of-five [n]
(= 0 (mod n 5)))
(defn- multiple-of-both-three-and-five [n]
(= 0 (mod n 15)))
(defn fizz-buzz []
(map #(if (multiple-of-both-three-and-five %)
"FizzBuzz"
(if (multiple-of-three %)
"Fizz"
(if (multiple-of-five %)
"Buzz"
%)))
(range 1 101)))
(fizz-buzz)
;; END - first solution
;; BEGIN - second solution (more elegant :)
(defn fizz-buzz-2 []
(map #(cond
(zero? (mod % 15)) "FizzBuzz"
(zero? (mod % 5)) "Buzz"
(zero? (mod % 3)) "Fizz"
:else %)
(range 1 101)))
(fizz-buzz-2)
;; END - second solution
;; BEGIN - third solution (TDDable :)
(defn- fizz-or-buzz-or-fizzbuzz [n]
(cond
(zero? (mod n 15)) "FizzBuzz"
(zero? (mod n 5)) "Buzz"
(zero? (mod n 3)) "Fizz"
:else n))
(defn -main [& args]
(map fizz-or-buzz-or-fizzbuzz (range 1 101)))
(-main)
(= (fizz-or-buzz-or-fizzbuzz 3) "Fizz") ;; true
(= (fizz-or-buzz-or-fizzbuzz 5) "Buzz") ;; true
(= (fizz-or-buzz-or-fizzbuzz 15) "FizzBuzz") ;; true
(= (fizz-or-buzz-or-fizzbuzz 16) 16) ;; true
(= (fizz-or-buzz-or-fizzbuzz 17) "Fizz") ;; false
;; END - third solution
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment