September 12, 2018
Just Juxt #29: Happy Numbers (4clojure #86)
Happy numbers are positive integers that follow a particular formula: take each individual digit, square it, and then sum the squares to get a new number. Repeat with the new number and eventually, you might get to a number whose squared sum is 1. This is a happy number. An unhappy number (or sad number) is one that loops endlessly. Write a function that determines if a number is happy or not.
(ns live.test
(:require [cljs.test :refer-macros [deftest is testing run-tests]]))
(defn char->ascii
([c]
(get {\0 48 \1 49 \2 50 \3 51 \4 52 \5 53 \6 54 \7 55 \8 56 \9 57} c)))
(defn happy [n]
(= 1 (some #{1 4}
(iterate
(fn [x] (reduce
#(+ %1 (apply * ((juxt identity identity)
(- (char->ascii %2) 48))))
0
(str x)))
n))))
(deftest happy-test
(is (= (happy 7) true))
(is (= (happy 986543210) true))
(is (= (happy 2) false))
(is (= (happy 3) false)))
(run-tests)