k-combinations 0.1.0

Efficient iterator over k-element combinations of a slice
Documentation
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
use std::ops::{Bound, RangeBounds};

/// Extension trait providing combination methods on slices.
///
/// ```
/// use combinations::Combinations;
///
/// let items = [1, 2, 3, 4];
///
/// // All pairs
/// let pairs: Vec<Vec<&i32>> = items.combinations(2).collect();
/// assert_eq!(pairs.len(), 6);
///
/// // Works on Vec too
/// let v = vec!["a", "b", "c"];
/// for combo in v.combinations(2) {
///     assert_eq!(combo.len(), 2);
/// }
/// ```
pub trait Combinations {
    type Item;

    /// Returns an iterator over all `k`-element combinations.
    ///
    /// ```
    /// use combinations::Combinations;
    ///
    /// let items = ["a", "b", "c"];
    /// let got: Vec<Vec<&&str>> = items.combinations(2).collect();
    /// assert_eq!(got, [vec![&"a", &"b"], vec![&"a", &"c"], vec![&"b", &"c"]]);
    ///
    /// // k=0 yields one empty combination
    /// assert_eq!(items.combinations(0).count(), 1);
    ///
    /// // k > len yields nothing
    /// assert!(items.combinations(10).next().is_none());
    /// ```
    fn combinations(&self, k: usize) -> CombinationIter<'_, Self::Item>;

    /// Returns an iterator over combinations of all sizes within `range`.
    ///
    /// Accepts any [`RangeBounds<usize>`]: `0..=k`, `1..3`, `..`, etc.
    /// Combinations are yielded in order of increasing size.
    ///
    /// ```
    /// use combinations::Combinations;
    ///
    /// // All subsets of size 1 or 2
    /// let items = [1, 2, 3];
    /// let got: Vec<Vec<&i32>> = items.combinations_range(1..=2).collect();
    /// assert_eq!(got.len(), 6); // C(3,1) + C(3,2) = 3 + 3
    ///
    /// // All 2^3 = 8 subsets
    /// assert_eq!(items.combinations_range(..).count(), 8);
    /// ```
    fn combinations_range(&self, range: impl RangeBounds<usize>) -> CombinationRangeIter<'_, Self::Item>;
}

impl<T> Combinations for [T] {
    type Item = T;
    fn combinations(&self, k: usize) -> CombinationIter<'_, T> {
        CombinationIter::new(self, k)
    }
    fn combinations_range(&self, range: impl RangeBounds<usize>) -> CombinationRangeIter<'_, T> {
        CombinationRangeIter::new(self, range)
    }
}

/// Iterator over all `k`-element combinations of a slice.
/// Each item is a `Vec<&T>`.
///
/// For slices with at most 64 elements, uses a bitmask (Gosper's hack)
/// internally for faster iteration. Falls back to index-based iteration
/// for larger slices.
///
/// Created by [`Combinations::combinations`].
///
/// ```
/// use combinations::Combinations;
///
/// let items = [10, 20, 30];
/// let mut iter = items.combinations(2);
///
/// assert_eq!(iter.next(), Some(vec![&10, &20]));
/// assert_eq!(iter.next(), Some(vec![&10, &30]));
/// assert_eq!(iter.next(), Some(vec![&20, &30]));
/// assert_eq!(iter.next(), None);
/// ```
pub struct CombinationIter<'a, T> {
    slice: &'a [T],
    state: State,
}

enum State {
    Bitmask {
        current: u64,
        limit: u64,
        done: bool,
    },
    Index {
        indices: Vec<usize>,
        done: bool,
    },
}

/// Mask with the lowest `bits` bits set.
fn low_mask(bits: u32) -> u64 {
    if bits >= 64 {
        u64::MAX
    } else if bits == 0 {
        0
    } else {
        (1u64 << bits) - 1
    }
}

impl<'a, T> CombinationIter<'a, T> {
    /// Fills `buf` with the next combination, returning `true` if one was
    /// produced. The buffer is cleared before each call, so callers can
    /// reuse the same `Vec` across iterations to avoid repeated allocation.
    ///
    /// ```
    /// use combinations::Combinations;
    ///
    /// let items = [1, 2, 3];
    /// let mut iter = items.combinations(2);
    /// let mut buf = Vec::new();
    /// while iter.next_into(&mut buf) {
    ///     println!("{buf:?}"); // no allocation after the first call
    /// }
    /// ```
    pub fn next_into(&mut self, buf: &mut Vec<&'a T>) -> bool {
        buf.clear();
        match &mut self.state {
            State::Bitmask {
                current,
                limit,
                done,
            } => {
                if *done {
                    return false;
                }

                let v = *current;

                let mut bits = v;
                while bits != 0 {
                    let i = bits.trailing_zeros();
                    buf.push(&self.slice[i as usize]);
                    bits &= bits - 1;
                }

                if v == 0 {
                    *done = true;
                    return true;
                }

                let t = v | (v - 1);
                if let Some(t1) = t.checked_add(1) {
                    let next = t1 | (((!t & t1) - 1) >> (v.trailing_zeros() + 1));
                    if next > *limit {
                        *done = true;
                    } else {
                        *current = next;
                    }
                } else {
                    *done = true;
                }

                true
            }
            State::Index { indices, done } => {
                if *done {
                    return false;
                }

                let k = indices.len();
                let n = self.slice.len();

                buf.extend(indices.iter().map(|&i| &self.slice[i]));

                let mut i = k;
                while i > 0 {
                    i -= 1;
                    if indices[i] < n - k + i {
                        indices[i] += 1;
                        for j in (i + 1)..k {
                            indices[j] = indices[j - 1] + 1;
                        }
                        return true;
                    }
                }

                *done = true;
                true
            }
        }
    }

    fn new(slice: &'a [T], k: usize) -> Self {
        let n = slice.len();
        if n <= 64 {
            if k > n {
                return Self {
                    slice,
                    state: State::Bitmask {
                        current: 0,
                        limit: 0,
                        done: true,
                    },
                };
            }
            let limit = low_mask(n as u32);
            let start = low_mask(k as u32);
            Self {
                slice,
                state: State::Bitmask {
                    current: start,
                    limit,
                    done: false,
                },
            }
        } else {
            if k > n {
                return Self {
                    slice,
                    state: State::Index {
                        indices: Vec::new(),
                        done: true,
                    },
                };
            }
            Self {
                slice,
                state: State::Index {
                    indices: (0..k).collect(),
                    done: false,
                },
            }
        }
    }
}

impl<'a, T> Iterator for CombinationIter<'a, T> {
    type Item = Vec<&'a T>;

    fn next(&mut self) -> Option<Self::Item> {
        let mut buf = Vec::new();
        if self.next_into(&mut buf) {
            Some(buf)
        } else {
            None
        }
    }
}

/// Iterator over combinations of multiple sizes within a range.
///
/// Created by [`Combinations::combinations_range`].
///
/// ```
/// use combinations::Combinations;
///
/// let items = [1, 2, 3];
/// let mut iter = items.combinations_range(0..=1);
///
/// assert_eq!(iter.next(), Some(vec![]));       // k=0
/// assert_eq!(iter.next(), Some(vec![&1]));     // k=1
/// assert_eq!(iter.next(), Some(vec![&2]));
/// assert_eq!(iter.next(), Some(vec![&3]));
/// assert_eq!(iter.next(), None);
/// ```
pub struct CombinationRangeIter<'a, T> {
    slice: &'a [T],
    current_k: usize,
    end_k: usize,
    inner: CombinationIter<'a, T>,
}

impl<'a, T> CombinationRangeIter<'a, T> {
    fn new(slice: &'a [T], range: impl RangeBounds<usize>) -> Self {
        let start_k = match range.start_bound() {
            Bound::Included(&s) => s,
            Bound::Excluded(&s) => s + 1,
            Bound::Unbounded => 0,
        };
        let end_k = match range.end_bound() {
            Bound::Included(&e) => e.min(slice.len()),
            Bound::Excluded(&0) => {
                return Self {
                    slice,
                    current_k: 1,
                    end_k: 0,
                    inner: CombinationIter::new(slice, 0),
                };
            }
            Bound::Excluded(&e) => (e - 1).min(slice.len()),
            Bound::Unbounded => slice.len(),
        };
        let current_k = start_k;
        let inner = CombinationIter::new(slice, current_k);
        Self {
            slice,
            current_k,
            end_k,
            inner,
        }
    }

    /// Fills `buf` with the next combination, returning `true` if one was
    /// produced. See [`CombinationIter::next_into`] for details.
    ///
    /// ```
    /// use combinations::Combinations;
    ///
    /// let items = [1, 2, 3];
    /// let mut iter = items.combinations_range(1..=2);
    /// let mut buf = Vec::new();
    /// let mut count = 0;
    /// while iter.next_into(&mut buf) {
    ///     count += 1;
    /// }
    /// assert_eq!(count, 6); // C(3,1) + C(3,2)
    /// ```
    pub fn next_into(&mut self, buf: &mut Vec<&'a T>) -> bool {
        loop {
            if self.inner.next_into(buf) {
                return true;
            }
            if self.current_k >= self.end_k {
                return false;
            }
            self.current_k += 1;
            self.inner = CombinationIter::new(self.slice, self.current_k);
        }
    }
}

impl<'a, T> Iterator for CombinationRangeIter<'a, T> {
    type Item = Vec<&'a T>;

    fn next(&mut self) -> Option<Self::Item> {
        let mut buf = Vec::new();
        if self.next_into(&mut buf) {
            Some(buf)
        } else {
            None
        }
    }
}

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

    #[test]
    fn choose_2() {
        let v = vec!["hej", "på", "dig"];
        let got: Vec<Vec<&&str>> = v.combinations(2).collect();
        assert_eq!(
            got,
            vec![
                vec![&"hej", &"på"],
                vec![&"hej", &"dig"],
                vec![&"på", &"dig"],
            ]
        );
    }

    #[test]
    fn choose_0() {
        let got: Vec<Vec<i32>> = [1, 2, 3]
            .combinations(0)
            .map(|c| c.into_iter().cloned().collect())
            .collect();
        assert_eq!(got, [[] as [i32; 0]]);
    }

    #[test]
    fn choose_all() {
        let got: Vec<Vec<i32>> = [1, 2, 3]
            .combinations(3)
            .map(|c| c.into_iter().cloned().collect())
            .collect();
        assert_eq!(got, [[1, 2, 3]]);
    }

    #[test]
    fn k_exceeds_len() {
        let got: Vec<Vec<i32>> = [1, 2]
            .combinations(5)
            .map(|c| c.into_iter().cloned().collect())
            .collect();
        assert!(got.is_empty());
    }

    #[test]
    fn count() {
        // C(6, 3) = 20
        assert_eq!([0; 6].combinations(3).count(), 20);
    }

    #[test]
    fn correct_combinations() {
        let items = [0, 1, 2, 3];
        let got: Vec<Vec<i32>> = items
            .combinations(2)
            .map(|c| c.into_iter().cloned().collect())
            .collect();
        // Co-lexicographic order (Gosper's hack / bitmask ascending)
        assert_eq!(got, [
            [0, 1], [0, 2], [1, 2],
            [0, 3], [1, 3],
            [2, 3],
        ]);
    }

    #[test]
    fn empty_slice() {
        let empty: &[i32] = &[];
        let got: Vec<Vec<i32>> = empty
            .combinations(0)
            .map(|c| c.into_iter().cloned().collect())
            .collect();
        assert_eq!(got, [[] as [i32; 0]]);
        assert!(empty.combinations(1).collect::<Vec<_>>().is_empty());
    }

    #[test]
    fn next_into_reuses_buffer() {
        let items = [1, 2, 3];
        let mut iter = items.combinations(2);
        let mut buf = Vec::new();
        let mut got = Vec::new();
        while iter.next_into(&mut buf) {
            got.push(buf.iter().map(|&&x| x).collect::<Vec<i32>>());
        }
        assert_eq!(got, [[1, 2], [1, 3], [2, 3]]);
    }

    #[test]
    fn range_inclusive() {
        let got: Vec<Vec<i32>> = [1, 2, 3]
            .combinations_range(0..=2)
            .map(|c| c.into_iter().cloned().collect())
            .collect();
        // k=0, then k=1, then k=2
        assert_eq!(got, [
            vec![],
            vec![1], vec![2], vec![3],
            vec![1, 2], vec![1, 3], vec![2, 3],
        ]);
    }

    #[test]
    fn range_exclusive() {
        let got: Vec<Vec<i32>> = [1, 2, 3]
            .combinations_range(1..3)
            .map(|c| c.into_iter().cloned().collect())
            .collect();
        assert_eq!(got, [
            vec![1], vec![2], vec![3],
            vec![1, 2], vec![1, 3], vec![2, 3],
        ]);
    }

    #[test]
    fn range_full() {
        // All 2^3 = 8 subsets of [1,2,3]
        let got: Vec<Vec<i32>> = [1, 2, 3]
            .combinations_range(..)
            .map(|c| c.into_iter().cloned().collect())
            .collect();
        assert_eq!(got, [
            vec![],
            vec![1], vec![2], vec![3],
            vec![1, 2], vec![1, 3], vec![2, 3],
            vec![1, 2, 3],
        ]);
    }

    #[test]
    fn range_empty() {
        let got: Vec<Vec<&i32>> = [1, 2].combinations_range(5..=6).collect();
        assert!(got.is_empty());
    }

    #[test]
    fn works_on_vec() {
        let v = vec![10, 20, 30];
        let got: Vec<Vec<i32>> = v
            .combinations(1)
            .map(|c| c.into_iter().cloned().collect())
            .collect();
        assert_eq!(got, [[10], [20], [30]]);
    }
}