2.8 KiB
		
	
	
	
	
	
	
	
			
		
		
	
	
			2.8 KiB
		
	
	
	
	
	
	
	
title, id, challengeType, forumTopicId
| title | id | challengeType | forumTopicId | 
|---|---|---|---|
| Hailstone sequence | 595608ff8bcd7a50bd490181 | 5 | 302279 | 
Description
n by:
- If nis1then the sequence ends
- If niseventhen the nextnof the sequence= n/2
- If nisoddthen the nextnof the sequence= (3 * n) + 1
Instructions
- Create a routine to generate the hailstone sequence for a number
- Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124and ending with8, 4, 2, 1
- 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!)
- xkcd (humourous).
Tests
tests:
  - text: <code>hailstoneSequence</code> is a function.
    testString: assert(typeof hailstoneSequence === 'function');
  - text: <code>hailstoneSequence()</code> should return <code>[[27,82,41,124,8,4,2,1], [351, 77031]]</code>
    testString: assert.deepEqual(hailstoneSequence(), res);
Challenge Seed
// noprotect
function hailstoneSequence() {
  const res = [];
  // Good luck!
  return res;
}
After Test
const res = [[27, 82, 41, 124, 8, 4, 2, 1], [351, 77031]];
Solution
// noprotect
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;
}