DEV Community

Discussion on: [Challenge] 🐝 FizzBuzz without if/else

Collapse
 
benwtrent profile image
Benjamin Trent • Edited

Clojure example.

I quite like Andrew's bit shift array example. Only think that its better to have a nil zeroth value so you get circuit breaking for free.

;; Array for grabbing appropriate string, if exists
(def fizzes [nil "Fizz" "Buzz" "FizzBuzz"])

;; boolean to integer conversion
(defn b-to-i [b]
  (bit-and 1 (bit-shift-right (Boolean/hashCode b) 1)))

(defn fizzit [n]
  (let [fizzed (b-to-i (= 0 (mod n 3)))                     ;1 if true
        buzzed (bit-shift-left (b-to-i (= 0 (mod n 5))) 1)  ;2 if true
        both (+ fizzed buzzed)]                             ;3 if both are true
    (or (get fizzes both) (str n)))
  )

(defn fizzbuzz [n]
  (map fizzit (range 1 (inc n))))

repl.it link