1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
use std::marker::PhantomData;

/// Heap's algorithm for generating permutations, recursive version.
///
/// The recursive algorithm supports slices of any size (even though
/// only a small number of elements is practical), and is generally
/// much faster than the iterative version.
pub fn heap_recursive<T, F>(xs: &mut [T], mut f: F) where F: FnMut(&mut [T])
{
    heap_unrolled_(xs.len(), xs, &mut f);
}

/// Unrolled version of heap's algorithm due to Sedgewick
fn heap_unrolled_<T>(n: usize, xs: &mut [T], f: &mut FnMut(&mut [T])) {
    match n {
        0 | 1 => f(xs),
        2 => {
            // [1, 2], [2, 1]
            f(xs);
            xs.swap(0, 1);
            f(xs);
        }
        3 => {
            // [1, 2, 3], [2, 1, 3], [3, 1, 2], [1, 3, 2], [2, 3, 1], [3, 2, 1]
            f(xs);
            xs.swap(0, 1);
            f(xs);
            xs.swap(0, 2);
            f(xs);
            xs.swap(0, 1);
            f(xs);
            xs.swap(0, 2);
            f(xs);
            xs.swap(0, 1);
            f(xs);
        }
        n => for i in 0..n {
            heap_unrolled_(n - 1, xs, f);
            let j = if n % 2 == 0 { i } else { 0 };
            xs.swap(j, n - 1);
        }
    }
}

/// Maximum number of elements we can generate permutations for using
/// Heap's algorithm (iterative version).
pub const MAXHEAP: usize = 16;

/// Heap's algorithm for generating permutations.
///
/// An iterative method of generating all permutations of a sequence.
///
/// Note that for *n* elements there are *n!* (*n* factorial) permutations.
pub struct Heap<'a, Data: 'a + ?Sized, T: 'a> {
    data: &'a mut Data,
    c: [u8; MAXHEAP],
    n: usize,
    // we can store up to 20! in 64 bits.
    index: u64,
    _element: PhantomData<&'a mut T>
}

impl<'a, T, Data: ?Sized> Heap<'a, Data, T>
    where Data: AsMut<[T]>
{
    /// Create a new `Heap`.
    pub fn new(data: &'a mut Data) -> Self {
        assert!(data.as_mut().len() <= MAXHEAP);
        Heap {
            data: data,
            c: [0; MAXHEAP],
            n: 0,
            index: 0,
            _element: PhantomData,
        }
    }

    /// Return a reference to the inner data
    pub fn get(&self) -> &Data {
        self.data
    }

    /// Return a mutable reference to the inner data
    pub fn get_mut(&mut self) -> &mut Data {
        self.data
    }

    /// Reset the permutations walker, without changing the data. It allows
    /// generating permutations again with the current state as starting
    /// point.
    pub fn reset(&mut self) {
        self.n = 0;
        for c in &mut self.c[..] { *c = 0; }
        self.index = 0;
    }

    /// Step the internal data into the next permutation and return
    /// a reference to it. Return `None` when all permutations
    /// have been visited.
    ///
    /// Note that for *n* elements there are *n!* (*n* factorial) permutations.
    pub fn next_permutation(&mut self) -> Option<&mut Data> {
        if self.index == 0 {
            self.index += 1;
            Some(self.data)
        } else {
            while self.n < self.data.as_mut().len() {
                let nb = self.n as u8;
                let nu = self.n;
                let c = &mut self.c;
                if c[nu] < nb {
                    // `n` acts like the current length - 1 of the slice we are permuting
                    // `c[n]` acts like `i` in the recursive algorithm
                    let j = if (nu + 1) % 2 == 0 { c[nu] as usize } else { 0 };
                    self.data.as_mut().swap(j, nu);
                    c[nu] += 1;
                    self.n = 0;
                    return Some(self.data);
                } else {
                    c[nu] = 0;
                    self.n += 1;
                }
            }
            None
        }
    }
}

/// Iterate the permutations
///
/// **Note:** You can also generate the permutations lazily by using
/// `.next_permutation()`.
impl<'a, Data: ?Sized, T> Iterator for Heap<'a, Data, T>
    where Data: AsMut<[T]> + ToOwned,
{
    type Item = Data::Owned;
    fn next(&mut self) -> Option<Self::Item> {
        match self.next_permutation() {
            None => None,
            Some(perm) => Some(perm.to_owned()),
        }
    }
}

/// Compute *n!* (*n* factorial)
pub fn factorial(n: usize) -> usize {
    let mut prod = 1;
    for x in 1..n + 1 { prod *= x; }
    prod
}

#[test]
fn first_and_reset() {
    let mut data = [1, 2, 3];
    let mut heap = Heap::new(&mut data);
    let mut perm123 = vec![[1, 2, 3], [2, 1, 3], [3, 1, 2], [1, 3, 2], [2, 3, 1], [3, 2, 1]];
    assert_eq!(heap.by_ref().collect::<Vec<_>>(), perm123);

    // test reset
    heap.reset();
    // for the 1,2,3 case this happens to work out to the reverse order
    perm123.reverse();
    assert_eq!(heap.by_ref().collect::<Vec<_>>(), perm123);
}

#[test]
fn permutations_0_to_6() {
    let mut data = [0; 6];
    for n in 0..data.len() {
        let count = factorial(n);
        for (index, elt) in data.iter_mut().enumerate() {
            *elt = index + 1;
        }
        let mut permutations = Heap::new(&mut data[..n]).collect::<Vec<_>>();
        assert_eq!(permutations.len(), count);
        permutations.sort();
        permutations.dedup();
        assert_eq!(permutations.len(), count);
        // Each permutation contains all of 1 to n
        assert!(permutations.iter().all(|perm| perm.len() == n));
        assert!(permutations.iter().all(|perm| (1..n + 1).all(|i| perm.iter().position(|elt| *elt == i).is_some())));
    }
}

#[test]
fn permutations_0_to_6_recursive() {
    let mut data = [0; 6];
    for n in 0..data.len() {
        let count = factorial(n);
        for (index, elt) in data.iter_mut().enumerate() {
            *elt = index + 1;
        }
        let mut permutations = Vec::with_capacity(count);
        heap_recursive(&mut data[..n], |elt| permutations.push(elt.to_owned()));
        println!("{:?}", permutations);
        assert_eq!(permutations.len(), count);
        permutations.sort();
        permutations.dedup();
        assert_eq!(permutations.len(), count);
        // Each permutation contains all of 1 to n
        assert!(permutations.iter().all(|perm| perm.len() == n));
        assert!(permutations.iter().all(|perm| (1..n + 1).all(|i| perm.iter().position(|elt| *elt == i).is_some())));
    }
}