Created
September 25, 2015 01:37
-
-
Save RichardJohnn/8e6af62e7272cf39e8b6 to your computer and use it in GitHub Desktop.
Heap's Algorithm for Permutation Generation in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//https://en.wikipedia.org/wiki/Heap%27s_algorithm | |
fn main(){ | |
let mut array = vec![1,2,3,4]; | |
generate(4, &mut array); | |
} | |
fn generate(n : usize, a : &mut Vec<usize>) { | |
if n == 1 { | |
println!("{:?}", a); | |
} | |
else { | |
for i in 0 .. n - 1 { | |
generate(n - 1, a); | |
if n % 2 == 0 { | |
a.swap(i, n - 1); | |
} | |
else { | |
a.swap(0, n - 1); | |
} | |
} | |
generate(n - 1, a); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment