How can I better log in memory allocation behavior using recursiveness in this example?

Asked

Viewed 37 times

-2

const yourself = {
  count: 0,
  fibonacci(n) {
    this.count++;
    **console.log(`${this.count}º vez - ${n}`);**
    if (n === 0 || n === 1) {
      return n;
    } else {
      return this.fibonacci(n - 1) + this.fibonacci(n - 2);
    }
  }
};

yourself.fibonacci(2);

Output from script 2 1 0, my wish 0 1 2, so I can better view the recursive stack structure where the last value of the call is the first to be released.

  • Instead of starting at zero and incrementing to 1, start at 1 and descend (count--) to zero.

  • I edited, gave a bad example.

  • 1

    But in this case the question is not simply to reverse the order, you will have to change your logic a little. Either insert the results into a list or calculate the values iteratively.

  • You are printing calls in order of stacking. What you are not able to view?

  • that your code will not give this exit 2 1 0 and yes the 1 1

  • use Return arr.Reverse();

  • I think the title of the question does not match the problem of fact.

  • @G.Bittencourt Thanks for the touch, I made a list, then I think something better.

Show 3 more comments

2 answers

1

The method reverse() reverts the order of the elements in an array.

var fib = function(n) {
  if (n === 1) {
    return [0, 1];
  } else {
    var arr = fib(n - 1);
    arr.push(arr[arr.length - 1] + arr[arr.length - 2]);
    return arr.reverse();
   
  }
};

console.log(fib(2));

I just don’t know if your script generates the expected result but the order is reversed.

1

See if this log clarifies you.

const yourself = {
  count: 0,
  log: [],
  
  fibonacci(n) {
    if (this.count === 0) this.log = [];
    this.count++;
    
    this.log.push(`Chamada ${this.count} - n=${n}`);
    console.log();
    if (n === 0 || n === 1) {
      return n;
    } else {
      this.log.push(`Empilhando fibonacci(${n-1}) - n=${n}`);
      let left = this.fibonacci(n - 1);
      this.log.push(`Desempilhando fibonacci(${n-1}) - n=${n}`);
      this.log.push(`Empilhando fibonacci(${n-2}) - n=${n}`);
      let right = this.fibonacci(n - 2);
      this.log.push(`Desmpilhando fibonacci(${n-2}) - n=${n}`);
      return left + right;
    }
  }
};

yourself.fibonacci(5);
console.log(yourself.log.join('\n'));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.