Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

154
Vistas
Collatz Sequence for all numbers from 1 to 10 stored in individual arrays

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) 
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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) 

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda