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

84
Visualizações
Best way to create an array that goes 1-50 then 49-1 with only 1 loop

I know the best way to create an array that goes 1-50 then 49-1 would be 2 loops but this exercise requires us to use only 1 loop

    let myArr = [];
    let reachedFifty = false;
    let x = 1;

    for(i=0;i<100;i++){
        
        if(x == 50){
            reachedFifty = true;
        }

        myArr[i] = x;

        if(reachedFifty){
            x--;
        }
        else{
            x++;
        }
        
    }

This accomplished the task but the instructor said I'm using too much ifs and there are better solutions.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

We can use the properties of the list to make this more efficient:

After filling the list with values it would look something like:

[1,2,3,4,.....,4,3,2,1]

We can see here that the list is symmetrical! By using this property, whenever we add a value on the "left" side, we can reflect it over to the right side:

let myArr = [];

for (let i = 0; i < 50; i++) {
  myArr[i] = i + 1;
  myArr[98 - i] = i + 1;
}

console.log(myArr)
.as-console-wrapper { max-height: 100% !important; }

Notice how we are using the index at 98 - i to reflect the changes across. This is because since there will be 99 total values, the value at index 0 should reflect to index 98, 1 to 97, etc.

I hope this helped answer your question! Please let me know if you need any further details or clarification :)

about 4 years ago · Juan Pablo Isaza Relatório

0

Why use any loops at all

const max = 50
const t1 = performance.now()

const arr = Array.from({ length: max * 2 - 1 }, (_, i) =>
  max - Math.abs(i - (max - 1)))

console.log(`Took ${performance.now() - t1}ms`)
console.info(arr)
.as-console-wrapper { max-height: 100% !important; }

This works by filling an array of length 99 with the evaluation of the expression

50 - |index - 49|

For example

  • i = 0 -> 50 - |-49| = 50 - 49 = 1
  • i = 1 -> 50 - |-48| = 50 - 48 = 2
  • ...
  • i = 49 -> 50 - |0| = 50 - 0 = 50
  • i = 50 -> 50 - |1| = 50 - 1 = 49
  • ...
  • i = 98 -> 50 - |49| = 50 - 49 = 1
about 4 years ago · Juan Pablo Isaza Relatório

0

Another solution is that you could check for i instead of x, that way you'll only have an if and no need for a boolean variable.

let myArr = [];
let x = 1;

for(i=0;i<100;i++){
    
    myArr[i] = x;

    if(i >= 49){
        x--;
    }
    else{
        x++;
    }
    
}

But the symmetrical list approach is better, I think.

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