I would be grateful if someone could explain me this bug.
I started to learn programming and came across this task:
Your task, is to create NxN multiplication table, of size provided in parameter. For example, when given size is 3, the returned value should be [[1,2,3],[2,4,6],[3,6,9]].
I came up with this solution.
const multiplicationTable = (size) => {
// creating the correct size of the multiplication table
let array = [];
array.length = size;
let array2 = [];
array2.length = size;
for (let m = 0; m < size; m++) {
array[m] = array2;
}
// assigning correct numbers
for (let i = 0; i < size; i++) {
let base = i + 1;
for (let j = 0; j < size; j++) {
let factor = j + 1;
array[i][j] = factor * base;
}
}
return array;
}
I know, that there might be more suitable solution, but I would like to ask, why this particular one does not work.
The problem seems to be with the variable "base". My intent was to set the value to 1, then hold it throughout the following nested loop, afterwards increase it by one and hold it again throughout iteration of another nested for loop.
The problem is that when I run the code, it does not hold the number 1, but it already sets itself to the last number. So my result when calling the function with a number 3 equals --> [ [ 3, 6, 9 ], [ 3, 6, 9 ], [ 3, 6, 9 ] ].
Thank you for any explanation, because for now, I cannot get my head around it. :)