📜  rust iterate 2D (1)

📅  最后修改于: 2023-12-03 14:47:10.277000             🧑  作者: Mango

Rust Iterate 2D

In Rust, iterating over a 2D array or matrix can be achieved using various methods depending on the use case.

Iterating over rows (outer loop)

One common use case is iterating over the rows (outer loop) of a 2D array or matrix. This can be done using the iter() method on the outermost array, which returns an iterator over its elements, and then iterating over each row using a nested loop.

let matrix = vec![
    vec![1, 2, 3],
    vec![4, 5, 6],
    vec![7, 8, 9],
];

for row in matrix.iter() {
    for element in row {
        println!("{}", element);
    }
}

Alternatively, the iter_mut() method can be used to iterate over mutable references to each row, allowing for in-place modifications:

let mut matrix = vec![
    vec![1, 2, 3],
    vec![4, 5, 6],
    vec![7, 8, 9],
];

for row in matrix.iter_mut() {
    row.reverse();
}
Iterating over columns (inner loop)

Another common use case is iterating over the columns (inner loop) of a 2D array or matrix. This can be achieved by transposing the matrix using the transpose() method, then iterating over its rows as columns:

let matrix = vec![
    vec![1, 2, 3],
    vec![4, 5, 6],
    vec![7, 8, 9],
];

let transposed = (0..matrix[0].len())
    .map(|j| matrix.iter().map(|row| row[j]).collect())
    .collect::<Vec<_>>();

for col in transposed.iter() {
    for element in col {
        println!("{}", element);
    }
}
Iterating over diagonals

Iterating over the diagonals of a 2D array or matrix can also be achieved using various methods depending on the use case.

One simple approach is to iterate over the indices of the matrix and utilize the fact that the sum of a row and column index is constant for each diagonal:

let matrix = vec![
    vec![1, 2, 3],
    vec![4, 5, 6],
    vec![7, 8, 9],
];

for i in 0..matrix.len() {
    for j in 0..matrix[i].len() {
        if i + j == matrix.len() - 1 {
            println!("{}", matrix[i][j]);
        }
    }
}

Alternatively, the zip method can be used to iterate over the diagonals:

let matrix = vec![
    vec![1, 2, 3],
    vec![4, 5, 6],
    vec![7, 8, 9],
];

let diagonal = matrix.iter()
    .enumerate()
    .map(|(i, row)| row[i])
    .collect::<Vec<_>>();

for element in diagonal.iter() {
    println!("{}", element);
}
Conclusion

Iterating over a 2D array or matrix in Rust can be achieved using various methods depending on the use case. Whether iterating over rows, columns, or diagonals, Rust provides powerful tools for working with multidimensional data structures.