Skip to content

Instantly share code, notes, and snippets.

@sivasankars
Created December 6, 2018 02:46
Show Gist options
  • Save sivasankars/0c1496c30997844fbc77498203f8238e to your computer and use it in GitHub Desktop.
Save sivasankars/0c1496c30997844fbc77498203f8238e to your computer and use it in GitHub Desktop.
Print Elements of a Matrix in Diagonal Order
var array = [
[[1], [2], [3], [4]],
[[5], [6], [7], [8]],
[[9], [10], [11], [12]],
[[13], [14], [15], [16]],
[[17], [18], [19], [20]]
];
function printAllDgl(array) {
var i = 0, j = 0, output = [];
// Loop to print each diagonal
for (var cnt = 0; cnt < 2 * array.length - 1; cnt++) {
if (cnt < array.length) {
i = cnt;
j = 0;
} else {
i = array.length - 1;
j = (cnt + 1) % array.length;
}
while (i >= 0 && j < array.length - 1) {
output.push(array[i][j][0])
i--;
j++;
}
}
return output.join(',');
}
console.log(printAllDgl(array));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment