Created
January 20, 2016 07:57
-
-
Save fvandepitte/4fd7e44a6c01d347015c to your computer and use it in GitHub Desktop.
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
import Data.List | |
import Data.Char | |
ps :: [[[Int]]] | |
ps = [] : map parts [1..] | |
where parts n = [n] : [x : p | x <- [1..n], p <- ps !! (n - x), x <= head p] | |
partitionsFor :: Int -> [[Int]] | |
partitionsFor = tail . (ps !!) | |
fillOrEmptyPartionToLength :: Int -> [Int] -> [Int] | |
fillOrEmptyPartionToLength x ys = | |
let needed = (x - length ys) | |
in fillOrEmptyPartionToLength' needed x ys | |
where fillOrEmptyPartionToLength' n x ys | n `elem` ys = ys ++ replicate n 0 | |
| otherwise = [] | |
filledPartitionsFor :: Int -> [[Int]] | |
filledPartitionsFor x = filter (/= []) $ map (fillOrEmptyPartionToLength x) $ partitionsFor x | |
count :: [Int] -> Int -> Int | |
count xs y = length $ filter (== y) xs | |
isSelfDescriptive :: [Int] -> Bool | |
isSelfDescriptive x = x == numberDescription x | |
numberDescription :: [Int] -> [Int] | |
numberDescription x = map (count x) [0 .. length x - 1] | |
toOutput :: [[Int]] -> String | |
toOutput [] = "No self-descriptive number found.\n" | |
toOutput xs = unlines $ map (concatMap show) xs | |
main = interact (toOutput . filter isSelfDescriptive . map numberDescription . filledPartitionsFor . read) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment