Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

155
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda