Diagonal Traverse

·

The image below shows what the problem requires. We need to traverse the 2-dimensional array diagonally to get a 1-dimemsional array.

We could follow what the problem says, simulate the process to get the output. But I found that's too boring. Then I found a solution which is very clever. Let's me use this algorithm to solve this problem.

Let's consider this 2-dimensional array.

``````1 2 3
3 4 5
7 8 9
``````

Express this array using element's indices.

``````[
(0,0), (0,1), (0,2),
(1,0), (1,1), (1,2),
(2,0), (2,1), (2,2),
]
``````

Group them diagonally, as the problem says.

``````[
[(0,0)],
[(0,1),(1,0)],
[(0,2),(1,1),(2,0)],
[(1,2),(2,1)],
[(2,2)]
]
``````

What pattern do you see? Yes, if the sum of the indices are the same, then they belong to the same group.

So now we can get groups one by one. One last thing to do, we need to adjust the direction. This is simple too. If the array's index is even, then reverse them.

That's all the process, let's see the code.

``````function findDiagonalOrder(mat: number[][]): number[] {

// grouping array
let groups: number[][][] = Array.from({ length: mat.length + mat[0].length - 1 }, _ => []);
for (let i = 0; i < mat.length; i++) {
for (let j = 0; j < mat[i].length; j++) {
groups[i + j].push([i, j]);
}
}

let result: number[] = [];
for (let i = 0; i < groups.length; i++) {
if (i % 2 === 0) {
groups[i].reverse();
}
for (let j = 0; j < groups[i].length; j++) {
result.push(mat[groups[i][j][0]][groups[i][j][1]]);
}
}

return result;
};
``````
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "url": "https://blog.yaox023.com/diagonal-traverse", "fetch_time": 1721040692000000000, "content_mime_type": "text/html", "warc_filename": "crawl-data/CC-MAIN-2024-30/segments/1720763514696.4/warc/CC-MAIN-20240715102030-20240715132030-00034.warc.gz", "warc_record_offset": 114897629, "warc_record_length": 18799, "token_count": 496, "char_count": 1534, "score": 4.0625, "int_score": 4, "crawl": "CC-MAIN-2024-30", "snapshot_type": "latest", "language": "en", "language_score": 0.785858690738678, "file_path": "/sailhome/yjruan/project/latent-lm/data/processed/finemath-4plus/finemath-4plus/train-00041-of-00064.parquet"}