How to generate all possible permutations and combinations of a vector of chars in Rust

1 Answer

0 votes
fn swap(arr: &mut [char], i: usize, j: usize) {
    arr.swap(i, j);
}

fn print_array(arr: &[char]) {
    for ch in arr {
        print!("{} ", ch);
    }
    println!();
}

// Recursive function to generate permutations
fn permute(arr: &mut [char], l: usize, r: usize) {
    if l == r {
        print_array(arr);
        return;
    }
    for i in l..=r {
        swap(arr, l, i);
        permute(arr, l + 1, r);
        swap(arr, l, i); // backtrack
    }
}

// Generate all combinations using bitmask
fn generate_combinations(arr: &[char]) {
    let size = arr.len();
    for mask in 1..(1 << size) {
        for i in 0..size {
            if mask & (1 << i) != 0 {
                print!("{} ", arr[i]);
            }
        }
        println!();
    }
}

fn main() {
    let mut input: Vec<char> = "abc".chars().collect();
    let size = input.len();

    println!("All permutations:");
    permute(&mut input, 0, size - 1);

    println!("\nAll combinations:");
    generate_combinations(&input);
}



/*
run:

All permutations:
a b c 
a c b 
b a c 
b c a 
c b a 
c a b 

All combinations:
a 
b 
a b 
c 
a c 
b c 
a b c 

*/

 



answered 2 hours ago by avibootz

Related questions

...