Here is a nice solution in JavaScript:
const getDigits = n => Array.from(String(n)).map(c => parseInt(c)) const getSquaredDigitsSum = n => getDigits(n) .map(n => n ** 2) .reduce((a, b) => a + b, 0) const isHappy = n => { const _isHappy = ([n, ...previousSteps]) => previousSteps.includes(n) ? n === 1 : _isHappy([getSquaredDigitsSum(n), n, ...previousSteps]) return _isHappy([n]) }
Then you can play with generators for instance:
const nextHappyNumber = n => (isHappy(n) ? n : nextHappyNumber(n + 1)) function* getHappyNumbersIterator() { let n = 0 while (true) { n = nextHappyNumber(n + 1) yield n } } const findFirstHappyNumbers = n => [...Array(n)].map(() => iterator.next().value) const happyNumbers = findFirstHappyNumbers(20) // => 1,7,10,13,19,23,28,31,32,44,49,68,70,79,82,86,91,94,97,100
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Here is a nice solution in JavaScript:
Then you can play with generators for instance: