Skip to content

Instantly share code, notes, and snippets.

@zaz
Last active December 17, 2015 04:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zaz/701554ac7545ca6f4ca8 to your computer and use it in GitHub Desktop.
Save zaz/701554ac7545ca6f4ca8 to your computer and use it in GitHub Desktop.
A simple solution to FizzBuzz — Clojure
(defn fizzbuzz?
"Determines what to print for a given number"
[x]
(condp #(zero? (mod %2 %1)) x
15 "fizzbuzz"
3 "fizz"
5 "buzz"
1 x))
(defn fizzbuzz
"Prints fizzes and buzzes for numbers between 1 and x"
[x]
(doseq [i (range 1 (inc x))]
(println (fizzbuzz? i))))
@zaz
Copy link
Author

zaz commented Dec 17, 2015

Notes:

(rem) can be used in place of (mod) with no change to the code — the difference in efficiency seems negligible.

(and (mod 3 x) (mod 5 x)) == (mod 15 x) because a number is divisible by 3 and 5 ⟷ the number is divisible by 15.

I prefer doseq, but dotimes can be used instead in the body of fizzbuzz:

(dotimes [i x]
    (println (fizzbuzz? (inc i))))

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