Self-describing numbers: Difference between revisions

m
Line 1,279:
 
Here are functions for generating all the self-describing numbers of a certain length. We capitalize on the fact (from Wikipedia) that a self-describing number of length n is a base-n number (i.e. all digits are 0..n-1).
<lang haskell>import DataControl.CharMonad (intToDigitforM_, replicateM)
import ControlData.MonadChar (replicateM, forM_intToDigit)
 
count :: Int -> [Int] -> Int
count x = length . filter (x ==)
 
-- allAll the combinations of n digits of base n.
-- aA base-n number areis represented as a list of ints, one per digit
-- one per digit
allBaseNNumsOfLength :: Int -> [[Int]]
allBaseNNumsOfLength = replicateM <*> (enumFromTo 0 . subtract 1)
replicateM
<*> (enumFromTo 0 . subtract 1)
 
isSelfDescribing :: [Int] -> Bool
isSelfDescribing num = all (\(i, x) -> x == count i num) $ zip [0 ..] num
all (\(i, x) -> x == count i num) $
zip [0 ..] num
 
-- translate itTranslated back into an integer in base-10
decimalize :: [Int] -> Int
decimalize = read . map intToDigit
Line 1,300 ⟶ 1,305:
main =
(print . concat) $
map decimalize
map decimalize . filter isSelfDescribing . allBaseNNumsOfLength <$> [1 .. 8]</lang>
. filter isSelfDescribing
. allBaseNNumsOfLength
<$> [1 .. 8]</lang>
{{Out}}
<pre>[1210,2020,21200,3211000,42101000]</pre>
9,655

edits