Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading