skip to Main Content

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


  1. Please use the below code:

    const n = 6;
    
    for (let i = 0; i < n; i++) {
      let index;
      if (i < Math.floor(n / 2)) {
        index = 1 + 2 * i;
      } else {
        index = 2 * (n - i - 1);
      }
      document.write(index + " ");
    }
    
    Login or Signup to reply.
  2. You could take a generator function* and switch oder of output depending of the index.

    function* indices(n, index = 0) {
        if (!n) return;
        if (index % 2) {
            yield index;
            yield* indices(n - 1, index + 1);
        } else {
            yield* indices(n - 1, index + 1);
            yield index;
        }
    }
    
    console.log(...indices(6)); // 1 3 5 4 2 0
    console.log(...indices(5)); // 1 3 4 2 0
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search