Today’s Programming Praxis problem is a pretty simple one, but it comes with a time limit. We have 15 minutes to write a function that finds all the happy numbers up to a given limit. The version below took me around 4 minutes. Let’s go into the explanation.
While we could write the function directly, we’ll split it up in two: one to determine if a single number is happy and one to get all the required happy numbers. We model the happy number algorithm with basic recursion. We keep a list of all previously “visited” numbers to detect loops.
isHappy :: (Read a, Integral a) => a -> Bool isHappy = f  where f _ 1 = True f xs n = notElem n xs && f (n:xs) (sum . map (^ 2) $ digits n) digits = map (read . return) . show
Once we know if a single number is happy, determining all of them is just a simple matter of filtering all the numbers less than the limit.
happyUpto :: (Read a, Integral a) => a -> [a] happyUpto n = filter isHappy [1..n - 1]
All that’s left is actually running the algorithm.
main :: IO () main = print $ happyUpto 50
Looks like everything’s working correctly. Of course, it would be somewhat embarrassing if it didn’t, since this is only a fraction more complicated than FizzBuzz.