Last active
August 29, 2015 14:15
-
-
Save enriclluelles/04cbba5bb1b99feeba62 to your computer and use it in GitHub Desktop.
Happy numbers kata
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
prevent overflow