freeCodeCamp/curriculum/challenges/english/10-coding-interview-prep/rosetta-code/hailstone-sequence.md

2.5 KiB

id title challengeType forumTopicId dashedName
595608ff8bcd7a50bd490181 Hailstone sequence 5 302279 hailstone-sequence

--description--

The Hailstone sequence of numbers can be generated from a starting positive integer, n by:

  • If n is 1 then the sequence ends
  • If n is even then the next n of the sequence = n/2
  • If n is odd then the next n of the sequence = (3 * n) + 1

The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.

The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud), or as the Collatz sequence.

--instructions--

  1. Create a routine to generate the hailstone sequence for a number
  2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
  3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. (But don't show the actual sequence!)

See also:

--hints--

hailstoneSequence should be a function.

assert(typeof hailstoneSequence === 'function');

hailstoneSequence() should return [[27,82,41,124,8,4,2,1], [351, 77031]]

assert.deepEqual(hailstoneSequence(), res);

--seed--

--after-user-code--

const res = [[27, 82, 41, 124, 8, 4, 2, 1], [351, 77031]];

--seed-contents--

function hailstoneSequence() {
  const res = [];


  return res;
}

--solutions--

function hailstoneSequence () {
  const res = [];

  function hailstone(n) {
    const seq = [n];
    while (n > 1) {
      n = n % 2 ? 3 * n + 1 : n / 2;
      seq.push(n);
    }
    return seq;
  }

  const h = hailstone(27);
  const hLen = h.length;
  res.push([...h.slice(0, 4), ...h.slice(hLen - 4, hLen)]);

  let n = 0;
  let max = 0;
  for (let i = 100000; --i;) {
    const seq = hailstone(i);
    const sLen = seq.length;

    if (sLen > max) {
      n = i;
      max = sLen;
    }
  }
  res.push([max, n]);

  return res;
}