Rosetta code hailstone sequence

the second element of the array the function returns is supposed to be
[351, 77031] but instead it returns [ 3711, 237 ], what’s wrong?
the first element of the array seems to be ok, why is it not working for the second one?

Your code so far


function hailstoneSequence() {
function sequence (n, bool) {
  if (bool) var actions = 0;
  else var arr = [];
  while (n !== 1) {
    if (bool) actions++;
    else arr.push(n);
    if (n % 2 === 0) n /= 2;
    else n = (3 * n) + 1;
  }
if (bool) return actions
else {
arr.push(1);
return arr.slice(0, 4).concat(arr.slice(-4, arr.length))}
}
var res = [];
var startInt = 3;
var longest = [0, 0];
while(startInt < 100000) {
let actions = sequence(startInt, true);
if (actions > longest[1]) longest = [startInt,actions];
startInt++
}
res.push(sequence(27, false));
res.push(longest);
return res;
}
console.log(hailstoneSequence())

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36.

Challenge: Hailstone sequence

Link to the challenge:

I think the challenge description is a bit misleading for this one. For the second part, they don’t want you to find out what the longest sequence for n < 100000 is - you can assume that you already know that the longest sequence is for n = 77031, so you only have to calculate and return the length of that particular sequence.

1 Like

still, why does it stop at 3711? it also says Potential infinite loop detected on line 19. Tests may fail if this is not changed. the line is

while (startInt < 100000)

Here’s the output I got when I copied your code and clicked “Run the Tests”:

[ [ 27, 82, 41, 124, 8, 4, 2, 1 ], [ 77031, 350 ] ]

So, you have the right numbers in the wrong order for the second part, except the 350 is off by one. My guess is you either forgot to count the initial number or the one at the end as part of the sequence.

To answer your specific question about the ouput, the console is resource limited in how many iterations it will actually do, while clicking “Run the Tests” is not as limited. I had the same problem as you with my console.log() statements stopping at about 12,000 iterations but would search all 100,000 if I ran the tests.

As for whether to check all numbers, I am firmly in the check them all camp. New code checks tests as well as tests check new code and both have bugs.

2 Likes

thanks, didn’t know it

That’s new to me, good to know that. I’ve added a solution for this particular challenge recently and simply took the provided value 77031 to check for the length of the sequence, instead of finding that value myself - because I ran into the “too many iterations” problem. Will update my solution later to include that functionality.

1 Like