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
use std::fmt;
use super::lazy_buffer::LazyBuffer;
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
pub struct Combinations<I: Iterator> {
k: usize,
indices: Vec<usize>,
pool: LazyBuffer<I>,
first: bool,
}
impl<I> fmt::Debug for Combinations<I>
where I: Iterator + fmt::Debug,
I::Item: fmt::Debug,
{
debug_fmt_fields!(Combinations, k, indices, pool, first);
}
pub fn combinations<I>(iter: I, k: usize) -> Combinations<I>
where I: Iterator
{
let mut indices: Vec<usize> = Vec::with_capacity(k);
for i in 0..k {
indices.push(i);
}
let mut pool: LazyBuffer<I> = LazyBuffer::new(iter);
for _ in 0..k {
if !pool.get_next() {
break;
}
}
Combinations {
k: k,
indices: indices,
pool: pool,
first: true,
}
}
impl<I> Iterator for Combinations<I>
where I: Iterator,
I::Item: Clone
{
type Item = Vec<I::Item>;
fn next(&mut self) -> Option<Self::Item> {
let mut pool_len = self.pool.len();
if self.pool.is_done() {
if pool_len == 0 || self.k > pool_len {
return None;
}
}
if self.first {
self.first = false;
} else if self.k == 0 {
return None;
} else {
let mut i: usize = self.k - 1;
if self.indices[i] == pool_len - 1 && !self.pool.is_done() {
if self.pool.get_next() {
pool_len += 1;
}
}
while self.indices[i] == i + pool_len - self.k {
if i > 0 {
i -= 1;
} else {
return None;
}
}
self.indices[i] += 1;
let mut j = i + 1;
while j < self.k {
self.indices[j] = self.indices[j - 1] + 1;
j += 1;
}
}
let mut result = Vec::with_capacity(self.k);
for i in self.indices.iter() {
result.push(self.pool[*i].clone());
}
Some(result)
}
}