How to sort each column of a matrix with strings in Rust

2 Answers

0 votes
fn transpose<'a>(matrix: &Vec<Vec<&'a str>>) -> Vec<Vec<&'a str>> {
    let cols = matrix[0].len();
    let mut transposed = vec![Vec::new(); cols];

    for row in matrix {
        for (col_index, &value) in row.iter().enumerate() {
            transposed[col_index].push(value);
        }
    }

    transposed
}

fn sort_columns(matrix: Vec<Vec<&str>>) -> Vec<Vec<&str>> {
    let mut transposed = transpose(&matrix);

    for column in &mut transposed {
        column.sort();
    }

    transpose(&transposed)
}

fn print_matrix(matrix: &Vec<Vec<&str>>) {
    for row in matrix {
        println!("{}", row.join(" "));
    }
}

fn main() {
    let matrix = vec![
        vec!["ccc", "zzzz", "x"],
        vec!["eeee", "aaa", "ffff"],
        vec!["uu", "hhh", "uuu"],
        vec!["bbb", "gg", "yyyyyy"],
    ];

    println!("Original Matrix:");
    print_matrix(&matrix);

    let sorted_matrix = sort_columns(matrix);

    println!("\nSorted Matrix:");
    print_matrix(&sorted_matrix);
}

   
    
/*
run:
    
Original Matrix:
ccc zzzz x
eeee aaa ffff
uu hhh uuu
bbb gg yyyyyy

Sorted Matrix:
bbb aaa ffff
ccc gg uuu
eeee hhh x
uu zzzz yyyyyy
    
*/

 



answered Jun 2 by avibootz
0 votes
fn sort_columns(matrix: &mut Vec<Vec<&str>>) {
    let rows = matrix.len();
    let cols = matrix[0].len();

    for col in 0..cols {
        // Extract column into a vector
        let mut column: Vec<&str> = matrix.iter().map(|row| row[col]).collect();

        // Sort the column
        column.sort();

        // Place sorted values back into the matrix
        for row in 0..rows {
            matrix[row][col] = column[row];
        }
    }
}

fn print_matrix(matrix: &Vec<Vec<&str>>) {
    for row in matrix {
        println!("{}", row.join(" "));
    }
}

fn main() {
    let mut matrix = vec![
        vec!["ccc", "zzzz", "yyyyyy"],
        vec!["eeee", "aaa", "ffff"],
        vec!["uu", "hhh", "uuu"],
        vec!["bbb", "gg", "x"],
    ];

    println!("Original Matrix:");
    print_matrix(&matrix);

    sort_columns(&mut matrix);

    println!("\nSorted Matrix:");
    print_matrix(&matrix);
}

   
    
/*
run:
    
Original Matrix:
ccc zzzz yyyyyy
eeee aaa ffff
uu hhh uuu
bbb gg x

Sorted Matrix:
bbb aaa ffff
ccc gg uuu
eeee hhh x
uu zzzz yyyyyy
    
*/

 



answered Jun 2 by avibootz
...