Narcissistic decimal number: Difference between revisions

→‎Haskell: -> representing unordered digit combinations as their power sums
m (→‎JS ES6: Updated the preamble)
(→‎Haskell: -> representing unordered digit combinations as their power sums)
Line 1,311:
As summing the nth power of the digits is unaffected by digit order, we can reduce the search space by filtering digit combinations of given length and arbitrary order, rather than filtering a full integer sequence.
 
In this way we can find the 25th narcissistic number after '''(sumlength $ (lengthconcatMap . digitGroups) <$>digitPowerSums [1 .. 7]) == 19447''' tests – an improvement on the exhaustive trawl through '''9926315''' integers.
 
<lang haskell>import Data.ListTuple (sort, unfoldrswap)
import Data.TupleList (swapunfoldr)
import Control.Arrow (second)
 
narcissiOfLength :: Int -> [Int]
narcissiOfLength n = filter (isDaffodil n) (digitPowerSums n)
 
let isDaffodil n ds = (sort . digitList . powerSum n) ds == ds
isDaffodil :: Int -> Int -> Bool
in powerSum n <$> filter (isDaffodil n) (digitGroups n)
isDaffodil e n = length ds == e && powerSum e ds == n
where
ds = digitList n
 
powerSum :: Int -> [Int] -> Int
Line 1,332 ⟶ 1,336:
else Nothing)
 
digitGroupsdigitPowerSums :: Int -> [[Int]]
digitGroupsdigitPowerSums nDigits = sortedDigitssnd <$> treeGrowth nDigits []
where
digitsnthPowers = ((,) <*> (^ nDigits)) <$> [0 .. 9]
treeGrowth n pps =
prependHeadMinus = ((<$>) . flip (:)) <*> (enumFromTo 0 . head)
sortedDigits n xs =
if n > 0
then sortedDigitstreeGrowth
(n - 1)
(if null xspps
then pure <$> digitsnthPowers
else foldMap prependHeadMinus xs)concatMap
else xs (\(pd, ps) ->
(second (ps +) <$> take (pd + 1) nthPowers))
pps)
else pps
 
main :: IO ()
--main = print $ 0length :$ concatconcatMap (narcissiOfLength <$>digitPowerSums [1 .. 7])</lang>
main = print $ 0 : concatMap narcissiOfLength [1 .. 7]</lang>
{{Out}}
<pre>[0,1,2,3,4,5,6,7,8,9,153,370,371,407,1634,8208,9474,54748,92727,93084,548834,1741725,4210818,9800817,9926315]</pre>
9,655

edits