`flatten` problem in iteration with arrays

Hi, my problem is the following:

fn get_submatrix(m: [[f32; 3]; 3], (row, column): (usize, usize)) -> [[f32; 2]; 2] {
    let mut result = [[0.0; 2]; 2];
    for i in 0..3 {
        for j in 0..3 {
            if !(i == row || j == column) {
                if let Some(number) = result.iter_mut().flatten().next() {
                    *number = m[i][j];
                }
            }
        }
    }
    result
}

fn main()  {
    let m = [[1.0,  1.0,  1.0],
             [3.0,  2.0,  1.0],
             [7.0,  3.0,  100.0],];
    let m3 = get_sub(m, (0, 0));
    println!("m3: {:?}", m3);
}

why the pointer in the result array don't advance in the iteration???

You're creating a whole new iterator each time you hit the if let Some(number) condition, and that new iterator starts from the beginning of result. I believe you wanted to do this:

fn get_submatrix(m: [[f32; 3]; 3], (row, column): (usize, usize)) -> [[f32; 2]; 2] {
    let mut result = [[0.0; 2]; 2];
    let mut result_iter = result.iter_mut().flatten();
    for i in 0..3 {
        for j in 0..3 {
            if !(i == row || j == column) {
                if let Some(number) = result_iter.next() {
                    *number = m[i][j];
                }
            }
        }
    }
    result
}

Playground.

2 Likes

Nice thanks!!!