Home > database >  Collatz Sequence for all numbers from 1 to 10 stored in individual arrays
Collatz Sequence for all numbers from 1 to 10 stored in individual arrays

Time:11-03

I want to produce Collatz Sequence for all numbers from 1 to 10 and all the produced sequences are stored in an array named innerArr that should change at every looping. And all those changed arrays are to be stored in outerArr (i.e. array of arrays). But:

1. Given for loop not incrementing (or decrementing) when there exists a while loop inside this for loop.

2. Given while loop is working only when there is no for loop covering it and n = (any number).

   let n,outerArr = []; 
   for (n = 1; n < 10; n  ) {
      let innerArr = [], i = 0;
      innerArr.push(n);
    
      while (n !== 1) {
        if (n % 2 == 0) {
          n = n / 2;
          innerArr.push(n);
        }  else {
          n = (3 * n)   1;
          innerArr.push(n);
        }
        i  ;
      }
      outerArr.push(innerArr);
    }
    console.log(outerArr) 

CodePudding user response:

The problem is, that your for loop, that tries to count n from 1 to 9, will never run through the end, because n is always reset to 1 in the while loop. Therefore you must separate the variables that count from 1 to 9, and the variable that is modified in the while loop.

Moreover, if you really want to cover the numbers from 1 to 10 as you say in your question, remember to use <= 10.

   let n,outerArr = []; 
   for (m = 1; m <= 10; m  ) {
      let n = m;
      let innerArr = [], i = 0;
      innerArr.push(n);
    
      while (n !== 1) {
        if (n % 2 == 0) {
          n = n / 2;
          innerArr.push(n);
        }  else {
          n = (3 * n)   1;
          innerArr.push(n);
        }
        i  ;
      }
      outerArr.push(innerArr);
    }
    console.log(outerArr) 
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related