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.
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 :)
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 = 1i = 1 -> 50 - |-48| = 50 - 48 = 2i = 49 -> 50 - |0| = 50 - 0 = 50i = 50 -> 50 - |1| = 50 - 1 = 49i = 98 -> 50 - |49| = 50 - 49 = 1Another 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.