Created
December 6, 2018 02:46
-
-
Save sivasankars/0c1496c30997844fbc77498203f8238e to your computer and use it in GitHub Desktop.
Print Elements of a Matrix in Diagonal Order
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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