loading...

re: Write a script to find "Happy Numbers" VIEW POST

FULL DISCUSSION
 

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
Code of Conduct Report abuse