javascript .push() adding to two arrays

Viewed 57

I want to find the longest series of collatz sequence under 100 and this code outputs 2, which is not the answer. when i watch the variables, whenever the .push()function adds something to the testary it also adds to the maxary. Why is it adding a value to the end of both?

var n;
var m;
var testary = [];
var maxary = [];
var max;
for(i=2;i<100;i++){
    n = i;
    m = i;
    while(n>1){
        if(n%2 == 0){
            testary.push(n);
            n = n/2;
    }   else if(n%2 != 0){
            testary.push(n);
            n = (3*n)+1;
    }
    if(testary.length>maxary.length){
        maxary = testary;
        max = m;
    }
}}
2 Answers

When you assign maxary = testary it assigns the reference of testary to maxary and whenever you try to add item using push to any one of them it will affect both the array as the value is changed at the reference in javascript

You can clone the array before assigning using spread syntax

var n;
var m;
var testary = [];
var maxary = [];
var max;
for(i=2;i<100;i++){
    n = i;
    m = i;
    while(n>1){
        if(n%2 == 0){
            testary.push(n);
            n = n/2;
    }   else if(n%2 != 0){
            testary.push(n);
            n = (3*n)+1;
    }
    if(testary.length>maxary.length){
        maxary = [...testary]; // clone the array
        max = m;
    }
}}

Interesting little puzzle. Never heard of Collatz before. Here is my take on it. It will return the top 10 sequence lengths and will show the "winning" sequence.

var arr,i,n,testary=[];
for(i=2;i<100;i++){ arr=[];n=i;
 do arr.push(n); 
 while ( (n = n%2 ? (3*n)+1 : n/2) >1 );
 testary.push(arr);
}
testary.sort((a,b)=>b.length-a.length).slice(0,10).forEach(e=>console.log(e[0],e.length))
// show longest found sequence:
console.log(testary[0].join(', '))

Related