Skip to content

Instantly share code, notes, and snippets.

@enriclluelles
Last active August 29, 2015 14: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 enriclluelles/04cbba5bb1b99feeba62 to your computer and use it in GitHub Desktop.
Save enriclluelles/04cbba5bb1b99feeba62 to your computer and use it in GitHub Desktop.
Happy numbers kata
(require ['clojure.set])
(def happy-numbers (set [1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100]))
(def not-happy-numbers (clojure.set/difference (set (range 1 100)) happy-numbers))
(defn decompose-in-digits [n]
(map #(Character/digit % 10) (str n)))
(def square #(*' % %))
(defn- happy? [n visited]
(if (contains? visited n)
false
(if (= n 1)
true
(let [ndigits (decompose-in-digits n)
sum-of-squares (apply + (map square ndigits))]
(happy? sum-of-squares (conj visited n))))))
(defn is-happy-number [n]
(happy? n #{}))
(defn is-happy-number-tail [a]
(loop [n a
visited #{}]
(if (contains? visited n)
false
(if (= n 1)
true
(let [ndigits (decompose-in-digits n)
sum-of-squares (apply + (map square ndigits))]
(recur sum-of-squares (conj visited n)))))))
(require ['clojure.test :refer :all])
(deftest check-happy
(doseq [x happy-numbers]
(is (is-happy-number x))))
(deftest check-not-happy
(doseq [x not-happy-numbers]
(is (not (is-happy-number x)))))
(run-tests)
@alvarogarcia7
Copy link

On line 8, why

(def square #(*' % %))

what is the star with the quote (*') operator? Different from * ? Lazy?

@lewang
Copy link

lewang commented Jul 24, 2015

prevent overflow

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