Initialize a two-dimensional array with the values shown in the table below
1 0 0 0 1 0 0 0 1 0
0 4 0 0 0 4 0 0 0 4
0 0 9 0 0 0 9 0 0 0
0 0 0 16 0 0 0 16 0 0
1 0 0 0 25 0 0 0 25 0
0 4 0 0 0 36 0 0 0 36
0 0 9 0 0 0 49 0 0 0
0 0 0 16 0 0 0 64 0 0
1 0 0 0 25 0 0 0 81 0
0 4 0 0 0 36 0 0 0 100
I tried doing a diagonal pattern but can’t seem to execute this pattern.
This is my diagonal code.
In the above diagram, the diagonal pattern seems to start after every 3 intervals replaced with zeros
function matrixPattern() {
let arr = [];
let len = 10;
for (let i = 0; i < len; i++) {
arr[i] = [];
for (let j = 0; j < len; j++) {
arr[i][j] = i !== j ? 0 : (i + 1) * (j + 1)
}
}
for (let i in arr) {
let line = '';
for (let j in arr[i]) {
line += arr[i][j] + 't';
}
console.log(line);
}
}
matrixPattern()
2
Answers
You can use modulo logic to identify which diagonals get the non-zero values. Note that the distance between two diagonals is not 3 but 4: the first diagonal starts at (0, 0), and the one at its right at (4, 0)!
The non-zero values are squares of the minimum distance to the left or the top. So they are not the multiplication of two different values, but two the same values. The inner assignment could be:
So:
Here is a solution that does not use modulo. It proceeds as follows.
n
xn
arrayarr
will all elements equal to zero.i
from0
ton-1
.diag = (i+1)**2
andarr[i][i] = diag
j = i+4
j < n
, setarr[i][j]
andarr[j][i]
todiag
thenj = j+4
i = n-1
we are finished with the construction ofarr
; else seti = i+1
and repeat with Step 3.In step 5, when setting
arr[i][j] = diag
,i
can be thought of as a row index andj
as a column index. When settingarr[j][i] = diag
,j
can be thought of as a row index andi
as a column index.Here is Ruby code to construct the array
arr
.arr
can be displayed as follows, confirming it is the desired array.