For example, I have some sequence that comes from pushing indexes to an array into middle contineously:
const n=6;
const arr=[];
for(let i=0;i<n;i++){
arr.splice(arr.length/2,0,i);
}
document.writeln(arr.join(" "));
which the result is 1 3 4 2 0.
But now I want a loop that iterates the indexes above, but not creating an index array first. How to I write that loop?
I tried:
const n=6;
for(let i=0;i<n;i++){
let index=null;
if(i==Math.floor(n/2)){
index=n-1;
}else if(i<n/2){
index=1+2*i;
}else{
index=2*(n-i-1);
}
document.write(index+" ");
}
but the result is 1 3 5 5 2 0 instead of 1 3 5 4 2 0. How to correct the loop (Or other built-in methods like reduce() that can have simpler lines of codes as solutions?)?
2
Answers
Please use the below code:
You could take a generator
function*
and switch oder of output depending of the index.