Created
August 20, 2024 18:17
-
-
Save yongjhih/be82663ec8466b8bb840bd4ac0f34e7a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/// | j j j j j | |
/// | 0 1 2 3 4 < j-index | |
/// ----+----------- round-th | |
/// i 0 | 0 1 2 3 4 round-0: [0,0] | |
/// i 1 | 1 2 3 4 5 round-1: [0,1][1,0] | |
/// i 2 | 2 3 4 5 6 round-2: [0,2][1,1][2,0] | |
/// i 3 | 3 4 5 6 7 round-3: [0,3][1,2][2,1][3,0] | |
/// i 4 | 4 5 6 7 8 round-4: [0,4][1,3][2,2][3,1][4,0] | |
/// round-5: [1,4][2,3][3,2][4,1] | |
/// round-6: [2,4][3,3][4,2] | |
/// round-7: [3,4][4,3] | |
/// round-8: [4,4] | |
/// [0,1,2], | |
/// [3,4,5], | |
/// [6,7,8], | |
/// travelR([[0,1,2],[3,4,5],[6,7,8]]).forEach(([it, j]) => { console.log(it[j]); }); | |
/// 0,3,1,6,4,2,7,5,8 | |
/// | |
/// [0], | |
/// [3,4,5], | |
/// [6,7,8], | |
/// 0,3,6,4,7,5,8 | |
/// travelR([[0],[3,4,5],[6,7,8]]).forEach(([it, j]) => { console.log(it[j]); }); | |
/// [0], | |
/// [3,4,5], | |
/// [6], | |
/// travelR([[0],[3,4,5],[6]]).forEach(([it, j]) => { console.log(it[j]); }); | |
/// 0,3,6,4,5 | |
function* diagonal(matrix) { | |
const rows = matrix.length; | |
const cols = Math.max(...matrix.map(it => it.length)); | |
// Traverse from top-left to bottom-right | |
for (let r = 0; r < rows + cols - 1; r++) { | |
let i = Math.min(r, rows - 1); | |
let j = r - i; | |
while (i >= 0 && j < cols) { | |
const row = matrix[i]; | |
console.log(`diagonal: ${i},${j}: ${row[j]}`); | |
if (j < row.length) yield [row, j]; | |
i--; | |
j++; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment