Narcissistic decimal number: Difference between revisions
Content added Content deleted
(→Haskell reduced search: (used swap in digitList)) |
(→JS ES6: -> Generating the unordered digit combinations as their power sums) |
||
Line 1,544:
In this way we can find the 25th narcissistic number after '''sum(map(compose(length, digitGroups), enumFromTo(1, 7))) === 19447''' tests – an improvement on the exhaustive trawl through '''9926315''' integers.
(Generating the unordered digit combinations directly as power sums allows faster testing later, and needs less space)
<lang JavaScript>(() => {
'use strict';
// DAFFODILS --------------------------------------------------------------
//
const
n > 0 ? filter(curry(isDaffodil)(n), digitPowerSums(n)) : [0];
// Do the decimal digits of N, each raised to the power E, sum to N itself ?
// isDaffodil :: Int -> Int -> Bool
const isDaffodil = (e, n) => {
const
powerSum = (n, xs) => xs.reduce((a, x) =>
digitList = n =>
cons((n % 10),
)
ds = digitList(n);
return e === ds.length && n === powerSum(e, ds);
};
// The subset of integers of n digits that actually need daffodil checking:
// (Flattened leaves of a tree of unique digit combinations, in which
// order is not significant. Digit sequence doesn't affect power summing)
// digitPowerSums :: Int
const digitPowerSums = nDigits => {
const
digitPowers = map(x => [x, pow(x, nDigits)], enumFromTo(0, 9)),
treeGrowth = (n, parentPairs) => (n > 0) ? (
treeGrowth(n - 1,
isNull(parentPairs) ? (
digitPowers
) : concatMap(([parentDigit, parentSum]) =>
map(([leafDigit, leafSum]) => //
[leafDigit, parentSum + leafSum],
take(parentDigit + 1, digitPowers)
),
parentPairs
))
) : parentPairs;
return map(snd, treeGrowth(nDigits, []));
};
// GENERIC FUNCTIONS ------------------------------------------------------
// enumFromTo :: Int -> Int -> Maybe Int -> [Int]
const enumFromTo = (m, n, step) => {
const d = (step || 1) * (n >= m ? 1 : -1);
return Array.from({
length: Math.floor((n - m) / d) + 1
}, (_, i) => m + (i * d));
};
// concatMap :: (a -> [b]) -> [a] -> [b]
const concatMap = (f, xs) => [].concat.apply([], xs.map(f));
Line 1,578 ⟶ 1,607:
const cons = (x, xs) => [x].concat(xs);
// 2 or more arguments
// curry :: Function -> Function
const curry = (f, ...args) => {
Line 1,586 ⟶ 1,616:
return go([].slice.call(args, 1));
};
// filter :: (a -> Bool) -> [a] -> [a]
const filter = (f, xs) => xs.filter(f);
//
const
// isNull :: [a] -> Bool
const isNull = xs => (xs instanceof Array) ? xs.length < 1 : undefined;
//
const
// pow :: Int -> Int -> Int
const pow = Math.pow
//
const
// show ::
// (a -> String) f, Num n =>
// a -> maybe f -> maybe n -> String
const show = JSON.stringify;
//
const
// TEST -------------------------------------------------------------------
// return length(concatMap(digitPowerSums, enumFromTo(0, 7)));
return show(
);
})();</lang>
|