Skip to content

Instantly share code, notes, and snippets.

@eduardobape
Last active May 1, 2022 19:15
Show Gist options
  • Save eduardobape/061c873d1aed0447226057e6848b3ea3 to your computer and use it in GitHub Desktop.
Save eduardobape/061c873d1aed0447226057e6848b3ea3 to your computer and use it in GitHub Desktop.
Get all diagonals of a matrix
// Displays the coordinates of all elements of the secondary diagonal and of all diagonals parallel to the secondary diagonal
fun printSecondaryDiagonals(numColumns: Int, numRows: Int) {
val diagonal = mutableListOf<Pair<Int, Int>>()
for (k in 0..numColumns + numRows - 2) {
for (j in 0..k) {
val i = k - j
if (i < numRows && j < numColumns) {
diagonal.add(Pair(i, j))
}
}
diagonal.clear()
}
}
// Displays the coordinates of all elements of the main diagonal and of all diagonals parallel to the main diagonal
fun printMainDiagonals(numColumns: Int, numRows: Int) {
val diagonal = mutableListOf<Pair<Int, Int>>()
for (k in 0..numColumns + numRows - 2) {
for (j in k downTo 0) {
val i = numColumns - 1 - k + j
if (j < numRows && i >= 0) {
diagonal.add(Pair(j, i))
}
}
diagonal.clear()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment