find all permutations of an array in rust

Here's an example implementation of finding all permutations of an array in Rust:

main.rs
fn permutation(arr: &mut [i32], left: usize, right: usize) {
    if left == right {
        println!("{:?}", arr);
    } else {
        for i in left..(right + 1) {
            arr.swap(left, i);
            permutation(arr, left + 1, right);
            arr.swap(left, i);
        }
    }
}
292 chars
12 lines

This function takes in an array arr, as well as the starting index left and ending index right of the subarray that we want to perform permutation on. Initially, the function is called with left = 0 and right = arr.len() - 1.

Within the function, we check if left and right are the same. If they are, we have reached the end of the subarray and print out the permutation.

Otherwise, we loop through the subarray from left to right and perform recursive calls to the permutation function after swapping elements in the subarray.

Here's an example usage of the function:

main.rs
let mut arr = [1, 2, 3];
permutation(&mut arr, 0, 2);
54 chars
3 lines

This will print out all permutations of the subarray [1, 2, 3]:

main.rs
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]
60 chars
7 lines

gistlibby LogSnag