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
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:
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.
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 paramterx = n*2
, which is what’s going on mathematically, multiple input by2
, return that result minus 2 for first index, repeat subtracting2
until indexn
.Included is logic to return an empty
Array
whenn
is0
or less. Adjust as you see fit.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):