blob: 7e7a80223a2ea7103c6354dc7a513c2378047be6 [file] [log] [blame]
Joel Galenson6f798712021-04-01 17:03:06 -07001use alloc::vec::Vec;
Jakub Kotura425e552020-12-21 17:28:15 +01002use std::fmt;
3
4use super::lazy_buffer::LazyBuffer;
5
6/// An iterator to iterate through all the `n`-length combinations in an iterator, with replacement.
7///
8/// See [`.combinations_with_replacement()`](../trait.Itertools.html#method.combinations_with_replacement) for more information.
9#[derive(Clone)]
10pub struct CombinationsWithReplacement<I>
11where
12 I: Iterator,
13 I::Item: Clone,
14{
Jakub Kotura425e552020-12-21 17:28:15 +010015 indices: Vec<usize>,
Jakub Kotura425e552020-12-21 17:28:15 +010016 pool: LazyBuffer<I>,
17 first: bool,
18}
19
20impl<I> fmt::Debug for CombinationsWithReplacement<I>
21where
22 I: Iterator + fmt::Debug,
23 I::Item: fmt::Debug + Clone,
24{
Joel Galenson6f798712021-04-01 17:03:06 -070025 debug_fmt_fields!(Combinations, indices, pool, first);
Jakub Kotura425e552020-12-21 17:28:15 +010026}
27
28impl<I> CombinationsWithReplacement<I>
29where
30 I: Iterator,
31 I::Item: Clone,
32{
33 /// Map the current mask over the pool to get an output combination
34 fn current(&self) -> Vec<I::Item> {
35 self.indices.iter().map(|i| self.pool[*i].clone()).collect()
36 }
37}
38
39/// Create a new `CombinationsWithReplacement` from a clonable iterator.
40pub fn combinations_with_replacement<I>(iter: I, k: usize) -> CombinationsWithReplacement<I>
41where
42 I: Iterator,
43 I::Item: Clone,
44{
Joel Galenson6f798712021-04-01 17:03:06 -070045 let indices: Vec<usize> = alloc::vec![0; k];
Jakub Kotura425e552020-12-21 17:28:15 +010046 let pool: LazyBuffer<I> = LazyBuffer::new(iter);
47
48 CombinationsWithReplacement {
Jakub Kotura425e552020-12-21 17:28:15 +010049 indices,
Jakub Kotura425e552020-12-21 17:28:15 +010050 pool,
51 first: true,
52 }
53}
54
55impl<I> Iterator for CombinationsWithReplacement<I>
56where
57 I: Iterator,
58 I::Item: Clone,
59{
60 type Item = Vec<I::Item>;
61 fn next(&mut self) -> Option<Self::Item> {
62 // If this is the first iteration, return early
63 if self.first {
64 // In empty edge cases, stop iterating immediately
Joel Galenson6f798712021-04-01 17:03:06 -070065 return if self.indices.len() != 0 && !self.pool.get_next() {
Jakub Kotura425e552020-12-21 17:28:15 +010066 None
67 // Otherwise, yield the initial state
68 } else {
69 self.first = false;
70 Some(self.current())
71 };
72 }
73
74 // Check if we need to consume more from the iterator
75 // This will run while we increment our first index digit
Joel Galenson6f798712021-04-01 17:03:06 -070076 self.pool.get_next();
Jakub Kotura425e552020-12-21 17:28:15 +010077
78 // Work out where we need to update our indices
79 let mut increment: Option<(usize, usize)> = None;
80 for (i, indices_int) in self.indices.iter().enumerate().rev() {
Joel Galenson6f798712021-04-01 17:03:06 -070081 if *indices_int < self.pool.len()-1 {
Jakub Kotura425e552020-12-21 17:28:15 +010082 increment = Some((i, indices_int + 1));
83 break;
84 }
85 }
86
87 match increment {
88 // If we can update the indices further
89 Some((increment_from, increment_value)) => {
90 // We need to update the rightmost non-max value
91 // and all those to the right
92 for indices_index in increment_from..self.indices.len() {
93 self.indices[indices_index] = increment_value
94 }
95 Some(self.current())
96 }
97 // Otherwise, we're done
98 None => None,
99 }
100 }
101}