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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
//! Streaming iterators on combinatorial objects (subsets, functions, ...).
//!
//! All these iterators works without allocating new memory after
//! their initialisation.
///
/// Interface for streaming iterators.
///
/// Similarly as in the streaming-iterator crate, the elements yielded by the iterator
/// are borrowed by the iterator.
/// A loop on such an iterator `iter` is written as follows.
///```ignore
///while let Some(item) = iter.next() {
///    ...
///}
///```
pub trait StreamingIterator<A>
where
    A: ?Sized,
{
    /// Return the next value of the iterator.
    fn next(&mut self) -> Option<&A>;

    /// Consume the iterator and return the number of elements yielded.
    fn count(mut self) -> usize
    where
        Self: Sized,
    {
        let mut count = 0;
        while let Some(_) = self.next() {
            count += 1;
        }
        count
    }
}

/// Iterator on subsets of `[n]`.
#[derive(Clone, Debug)]
pub struct Subsets {
    n: usize,
    data: Vec<usize>,
    untouched: bool,
}

impl Subsets {
    /// Create an iterator on the subsets of `[n]`.
    pub fn new(n: usize) -> Self {
        Subsets {
            n,
            data: Vec::with_capacity(n),
            untouched: true,
        }
    }
}

impl StreamingIterator<[usize]> for Subsets {
    fn next(&mut self) -> Option<&[usize]> {
        if self.untouched {
            //skip the first step
            self.untouched = false;
        } else {
            let mut k = self.n;
            loop {
                if k == 0 {
                    return None;
                }
                k -= 1;
                if self.data.last() != Some(&k) {
                    break;
                }
                let _ = self.data.pop();
            }
            self.data.push(k);
        }
        Some(&self.data)
    }
}

/// Iterator on functions from [n] to [k].
#[derive(Clone, Debug)]
pub struct Functions {
    n: usize,
    k: usize,
    data: Vec<usize>,
    untouched: bool,
}

impl Functions {
    /// Create an iterator on the function from `[n]` to `[k]`.
    pub fn new(n: usize, k: usize) -> Self {
        Functions {
            n,
            k,
            data: vec![0; n],
            untouched: true,
        }
    }
}

impl StreamingIterator<[usize]> for Functions {
    fn next(&mut self) -> Option<&[usize]> {
        if self.untouched {
            //skip the first step
            self.untouched = false;
        } else {
            let mut i = 0;
            while i < self.n && self.data[i] == self.k - 1 {
                i += 1;
            }
            if i == self.n {
                return None;
            } else {
                self.data[i] += 1;
                for j in 0..i {
                    self.data[j] = 0;
                }
            }
        }
        Some(&self.data)
    }
}

/// Iterator on subsets of [n] with `k` elements represented by
/// an increasing array.
#[derive(Clone, Debug)]
pub struct Choose {
    n: usize,     // total number of elements
    k: usize,     // number of elements chosen
    fixed: usize, // number of elements fixed
    data: Vec<usize>,
    untouched: bool,
}

impl Choose {
    /// Subsets of [n] with k elements.
    pub fn new(n: usize, k: usize) -> Self {
        Self::with_fixed_part(n, k, 0)
    }
    /// Subsets of [n] with k elements that contain [fixed].  
    pub fn with_fixed_part(n: usize, k: usize, fixed: usize) -> Self {
        assert!(fixed <= k && k <= n);
        Choose {
            n,
            k,
            fixed,
            data: (0..k).collect(),
            untouched: true,
        }
    }
}

impl StreamingIterator<[usize]> for Choose {
    fn next(&mut self) -> Option<&[usize]> {
        if self.untouched {
            self.untouched = false;
        } else {
            let mut i = self.k;
            while {
                // do ..
                if i <= self.fixed {
                    return None;
                } else {
                    i -= 1
                }; // .. while ..
                self.data[i] == self.n - self.k + i // loop condition
            } {}
            self.data[i] += 1;
            for j in (i + 1)..self.k {
                self.data[j] = self.data[i] + j - i;
            }
        }
        Some(&self.data)
    }
}

/// Iterator on the partitions of [n] into two sets of respective size `k` and `n-k`.
#[derive(Clone, Debug)]
pub struct Split {
    choose: Choose,
    second_part: Vec<usize>,
}

impl Split {
    /// Create an iterator on partitions of [n] into two sets of respective size `k` and `n-k`.
    pub fn new(n: usize, k: usize) -> Self {
        Self::with_fixed_part(n, k, 0)
    }
    /// Create an iterator on partitions of [n] into two sets of respective size `k`
    /// and `n-k+fixed` that both contain `[fixed]`.
    pub fn with_fixed_part(n: usize, k: usize, fixed: usize) -> Self {
        let second_part_size = n - k + fixed;
        Split {
            choose: Choose::with_fixed_part(n, k, fixed),
            second_part: (0..second_part_size).collect(),
        }
    }
    /// Yield next element of the iterator.
    ///
    /// Because of the type of this function, `Split` does not implement
    /// the trait `StreamingIterator`.
    pub fn next(&mut self) -> Option<(&[usize], &[usize])> {
        let s = self.choose.fixed;
        let k = self.choose.k;
        let n = self.choose.n;
        match self.choose.next() {
            Some(p) => {
                let mut j = s;
                for i in s..=k {
                    let start = if i == s { s } else { p[i - 1] + 1 };
                    let end = if i == k { n } else { p[i] };
                    for v in start..end {
                        self.second_part[j] = v;
                        j += 1;
                    }
                }
                Some((p, &self.second_part))
            }
            None => None,
        }
    }
}

/// Iterator on the injections from [k] to [n].
#[derive(Clone, Debug)]
pub struct Injection {
    n: usize,
    k: usize,
    data: Vec<usize>,
    index: Vec<usize>,
    fixed: usize, // number of fixed elements
    untouched: bool,
}

impl Injection {
    /// Iterator on the injections from `[k]` to `[n]` that stabilize `[fixed]`.
    pub fn with_fixed_part(n: usize, k: usize, fixed: usize) -> Injection {
        assert!(k <= n);
        assert!(fixed <= k);
        Injection {
            n,
            k,
            data: (0..n).collect(),
            index: (0..k).collect(),
            fixed,
            untouched: true,
        }
    }

    /// Iterator on the injections from [k] to [n].
    pub fn new(n: usize, k: usize) -> Injection {
        Self::with_fixed_part(n, k, 0)
    }

    ///Iterator on the permutations of [n].
    pub fn permutation(n: usize) -> Injection {
        Self::new(n, n)
    }

    #[inline]
    fn set_index(&mut self, i: usize, val: usize) {
        let old_val = self.index[i];
        self.index[i] = val;
        self.data.swap(i, old_val);
        self.data.swap(i, val);
    }
}

impl StreamingIterator<[usize]> for Injection {
    fn next(&mut self) -> Option<&[usize]> {
        if self.untouched {
            self.untouched = false;
        } else {
            if self.k == self.fixed {
                return None;
            }; // Avoiding negative value on next line
            let mut i = self.k - 1;
            while self.index[i] == self.n - 1 {
                if i == self.fixed {
                    return None;
                };
                i -= 1
            }
            let vi = self.index[i] + 1;
            self.set_index(i, vi);
            for j in (i + 1)..self.k {
                self.set_index(j, j);
            }
        }
        Some(&self.data[0..self.k])
    }
}

///Tests
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn unit_subsets() {
        assert_eq!(1, Subsets::new(0).count());
        assert_eq!(2, Subsets::new(1).count());
        assert_eq!(16, Subsets::new(4).count());
    }

    #[test]
    fn unit_choose() {
        assert_eq!(120, Choose::new(10, 3).count());
        assert_eq!(3, Choose::new(3, 1).count());
        assert_eq!(1, Choose::new(0, 0).count());
        assert_eq!(1, Choose::new(2, 2).count());
        assert_eq!(120, Choose::with_fixed_part(11, 4, 1).count());
        assert_eq!(1, Choose::with_fixed_part(5, 5, 4).count());
        assert_eq!(1, Choose::with_fixed_part(4, 4, 4).count());
        assert_eq!(1, Choose::with_fixed_part(6, 2, 2).count());
        assert_eq!(1, Choose::with_fixed_part(0, 0, 0).count());
    }

    #[test]
    fn unit_split() {
        let mut iter = Split::with_fixed_part(12, 5, 2);
        let mut count = 0;
        while let Some((_a, _b)) = iter.next() {
            count += 1;
        }
        assert_eq!(120, count);
    }

    #[test]
    fn unit_injection() {
        assert_eq!(60, Injection::new(5, 3).count());
        assert_eq!(1, Injection::new(42, 0).count());
        assert_eq!(720, Injection::permutation(6).count());
        assert_eq!(20, Injection::with_fixed_part(8, 5, 3).count());
        assert_eq!(1, Injection::with_fixed_part(6, 2, 2).count());
        assert_eq!(1, Injection::new(0, 0).count());
    }
}