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
use std::fmt;
use super::lazy_buffer::LazyBuffer;
#[derive(Clone)]
pub struct CombinationsWithReplacement<I>
where
I: Iterator,
I::Item: Clone,
{
k: usize,
indices: Vec<usize>,
max_index: usize,
pool: LazyBuffer<I>,
first: bool,
}
impl<I> fmt::Debug for CombinationsWithReplacement<I>
where
I: Iterator + fmt::Debug,
I::Item: fmt::Debug + Clone,
{
debug_fmt_fields!(Combinations, k, indices, max_index, pool, first);
}
impl<I> CombinationsWithReplacement<I>
where
I: Iterator,
I::Item: Clone,
{
fn current(&self) -> Vec<I::Item> {
self.indices.iter().map(|i| self.pool[*i].clone()).collect()
}
}
pub fn combinations_with_replacement<I>(iter: I, k: usize) -> CombinationsWithReplacement<I>
where
I: Iterator,
I::Item: Clone,
{
let indices: Vec<usize> = vec![0; k];
let pool: LazyBuffer<I> = LazyBuffer::new(iter);
CombinationsWithReplacement {
k,
indices,
max_index: 0,
pool,
first: true,
}
}
impl<I> Iterator for CombinationsWithReplacement<I>
where
I: Iterator,
I::Item: Clone,
{
type Item = Vec<I::Item>;
fn next(&mut self) -> Option<Self::Item> {
if self.first {
return if self.k != 0 && !self.pool.get_next() {
None
} else {
self.first = false;
Some(self.current())
};
}
if self.pool.get_next() {
self.max_index = self.pool.len() - 1;
}
let mut increment: Option<(usize, usize)> = None;
for (i, indices_int) in self.indices.iter().enumerate().rev() {
if indices_int < &self.max_index {
increment = Some((i, indices_int + 1));
break;
}
}
match increment {
Some((increment_from, increment_value)) => {
for indices_index in increment_from..self.indices.len() {
self.indices[indices_index] = increment_value
}
Some(self.current())
}
None => None,
}
}
}