I have an array of n x n
elements, and I want to fill its diagonals with the same values as follows:
ex. n = 3:
0 1 2
3 0 1
4 3 0
arr = [0, 1, 2, 3, 0, 1, 4, 3, 0]
ex. n = 4;
0 1 2 3
4 0 1 2
5 4 0 1
6 5 4 0
arr = [0, 1, 2, 3, 4, 0, 1, 2, 5, 4, 0, 1, 6, 5, 4, 0]
I was able to fill upper half of the array using the following code, but got stuck with the rest:
var n = 3;
var values = [0, 1, 2, 3, 4]
var a = [];
for (var i = 0; i < n; i++) {
for (var j = 0; j < n; j++) {
a[j * n + i] = values[i - j];
}
}
/* Result
0 1 2
0 1
0
arr = [0, 1, 2, undefined, 0, 1, undefined, undefined, 0] */
Length of values
array is 2 * n - 1
, which is the count of diagonals of the array.
Any ideas how to fill the whole array?