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.
>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 🙂