Permutations by swapping: Difference between revisions

m
Minor edit to Rust code
m (Added link to WP page on Heap's algorithm. The pseudocode presented on that page has been corrected since this task was created.)
m (Minor edit to Rust code)
Line 2,802:
<lang rust>// Implementation of Heap's algorithm.
// See https://en.wikipedia.org/wiki/Heap%27s_algorithm#Details_of_the_algorithm
fn generate<T, F>(a: &mut [T], mut output: F)
where
F: FnMutFn(&[T], isize),
{
let n = a.len();
let mut c = vec![0; n];
let mut i = 1;
output(a)let mut sign = 1;
generateoutput(a, psign);
while i < n {
if c[i] < i {
Line 2,817 ⟶ 2,818:
a.swap(c[i], i);
}
output(a)sign = -sign;
output(a, sign);
c[i] += 1;
i = 1;
Line 2,827 ⟶ 2,829:
}
 
fn print_permutationsprint_permutation<T: std::fmt::Debug>(a: &mut [T], sign: isize) {
letprintln!("{:?} mut{}", evena, = truesign);
let p = move |x: &[T]| {
println!("{:?} {}", x, if even { "+1" } else { "-1" });
even = !even;
};
generate(a, p);
}
 
Line 2,839 ⟶ 2,836:
println!("Permutations and signs for three items:");
let mut a = vec![0, 1, 2];
print_permutationsgenerate(&mut a, print_permutation);
 
println!("\nPermutations and signs for four items:");
let mut b = vec![0, 1, 2, 3];
print_permutationsgenerate(&mut b, print_permutation);
}</lang>
 
{{out}}
<pre>
[0, 1, 2] +1
Permutations and signs for three items:
[0, 1, 2] +1
[1, 0, 2] -1
[2, 0, 1] +1
[0, 2, 1] -1
[1, 2, 0] +1
[2, 1, 0] -1
 
Permutations and signs for four items:
[0, 1, 2, 3] +1
[1, 0, 2, 3] -1
[2, 0, 1, 3] +1
[0, 2, 1, 3] -1
[1, 2, 0, 3] +1
[2, 1, 0, 3] -1
[3, 1, 0, 2] +1
[1, 3, 0, 2] -1
[0, 3, 1, 2] +1
[3, 0, 1, 2] -1
[1, 0, 3, 2] +1
[0, 1, 3, 2] -1
[0, 2, 3, 1] +1
[2, 0, 3, 1] -1
[3, 0, 2, 1] +1
[0, 3, 2, 1] -1
[2, 3, 0, 1] +1
[3, 2, 0, 1] -1
[3, 2, 1, 0] +1
[2, 3, 1, 0] -1
[1, 3, 2, 0] +1
[3, 1, 2, 0] -1
[2, 1, 3, 0] +1
[1, 2, 3, 0] -1
</pre>
1,777

edits