skip to Main Content

How to make the two nested loops into one loop for the function? Please add the explanation to the code in your answer. You can add more explanation on strategy guideline to reduce nested loops for other common cases for perfect answer. Thanks!

function countDistance (n) {
  const distance = new Array(n).fill(0)
  for (let i = 1; i < n; i++) {
    for (let j = 1; j <= i; j++) {
      distance[i - j] += 2
    }
  }

  return distance
}

3

Answers


  1. Look at the output and determine what the function is a actually doing. Then determine if nested loops are the best way to achieve this.

    In this instance the function produces an array of length n, where the contents are n minus the items index multiplied by 2. We could also determine this from the code, but sometimes it’s just easier to look at the output.

    Now we know that refactoring the code is simple:

    function countDistance2 (n) {
      const distance = new Array(n).fill(0)
      for (let i = 1; i < n; i++) {
        distance[i - 1] = (n - i) * 2;
      }
    
      return distance
    }
    
    var n = 10
    
    console.log(countDistance2(n))

    Sometime you can’t escape nested loops and sometimes the solution is more complex for us human compilers to understand. At that point, you need to look at the size of the expected data set, is the performance improvement worth the added code complexity/readability.

    Login or Signup to reply.
  2. You can use Array.from() and include an option to adjust the input variables, that is, your mathematical operations in the inner loop, below at the default paramter x = n*2, which is what’s going on mathematically, multiple input by 2, return that result minus 2 for first index, repeat subtracting 2 until index n.

    Included is logic to return an empty Array when n is 0 or less. Adjust as you see fit.

    function cd(n, x = n*2) {
      return Array.from({length:n <= 0 ? 0 : n}, () => x-=2)
    }
    
    Login or Signup to reply.
  3. You don’t need to fill the array initially, that just waste of time, you fill it anyway with new values later. Plus you could use while loop and fill it from the end, might look more natural (incrementing distance):

    function countDistance(n) {
      const distance = Array(n), upper = n - 1;
      while(n--) distance[n] = (upper - n) * 2;
      return distance;
    }
    
    console.log(...countDistance(10));
    ` Chrome/122
    -------------------------------------------------------------------------------------
    >                  n=10       |      n=100       |      n=1000      |     n=10000    
    Alexander      1.00x x10m 195 |  1.00x   x1m 179 |  1.00x x100k 170 |  1.00x x10k 157
    JohnP          2.05x x10m 400 |  1.40x   x1m 251 |  1.24x x100k 211 |  1.28x x10k 201
    guest271314   17.18x  x1m 335 | 14.02x x100k 251 | 14.76x  x10k 251 | 15.92x  x1k 250
    -------------------------------------------------------------------------------------
    https://github.com/silentmantra/benchmark `
    
    let $length = 10;
    
    // @benchmark Alexander
    function countDistance(n) {
      const distance = Array(n), upper = n - 1;
      while(n--) distance[n] = (upper - n) * 2;
      return distance;
    }
    
    // @run
    countDistance($length);
    
    // @benchmark guest271314
    function cd(n, x = n*2) {
      return Array.from({length:n <= 0 ? 0 : n}, () => x-=2)
    }
    // @run
    cd($length);
    
    // @benchmark JohnP
    function countDistance2 (n) {
      const distance = new Array(n).fill(0)
      for (let i = 1; i < n; i++) {
        distance[i - 1] = (n - i) * 2;
      }
    
      return distance
    }
    // @run
    countDistance2($length);
    
    
    /*@end*/eval(atob('e2xldCBlPWRvY3VtZW50LmJvZHkucXVlcnlTZWxlY3Rvcigic2NyaXB0Iik7aWYoIWUubWF0Y2hlcygiW2JlbmNobWFya10iKSl7bGV0IHQ9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgic2NyaXB0Iik7dC5zcmM9Imh0dHBzOi8vY2RuLmpzZGVsaXZyLm5ldC9naC9zaWxlbnRtYW50cmEvYmVuY2htYXJrL2xvYWRlci5qcyIsdC5kZWZlcj0hMCxkb2N1bWVudC5oZWFkLmFwcGVuZENoaWxkKHQpfX0='));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search