skip to Main Content

may beginner problem?

i implement simple recurse code.
but, it does not work.
what is wrong?

or more simple way to do?

first block is tried recurse code,
second block is sample non-recurse code. both results are should be same.

I must use recursive code.

const total = 2;

// vvvvvvvv wrong code start
let accum = 0;
let obj = [];

const loop = (total, accum, obj) => {
  for (let i = 0; i < total; i++) {
    
    obj.push(i);
    
    if (total > accum) {      
      accum++;
      loop(total, accum, obj);
    } else {
      console.log(obj);
    }
          
    obj.pop();
  }
}

loop(total, accum, obj);
// ^^^^^^^^ wrong code end

console.log('-----------------------------');

// vvvvvvvv expect result
for (let i = 0; i < total; i++) {
    for (let j = 0; j < total; j++) { 
        console.log([i, j]);
    }
}

2

Answers


  1. You are console logging the obj but also popping from it. You need to wait until it has the length you want

    This works better

    const total = 2;
    let obj = [];
    
    const loop = (total, obj) => {
      if (obj.length === total) {
        console.log(obj.slice()); // make sure it logs a copy of the object
        return;
      }
      for (let i = 0; i < total; i++) {
        obj.push(i);
        loop(total, obj);
        obj.pop();
      }
    };
    loop(total, obj);
    Login or Signup to reply.
  2. Delegate the inner loop to the same function and pass the current loop state as an arguments:

    const loop = (to, arr = [], from = 0, level = 0) => {
      
      for (let i = from; i < to; i++) {
        arr.push([i, level]);
        if(level + 1 === to) return false;
        if(!loop(to, arr, i, level + 1)){
          break;
        }
      }
      return arr;
    }
    
    //console.log(loop(2));
    console.log(loop(3));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search