Skip to content

Commit 4a58e19

Browse files
committed
Avoid redundant Combinations::k
`Combinations::k` denotes the number of elements that we want to draw. However, this information can easily be inferred from `indices.len`. Since `indices` is a `Vec`, it should still be O(1). (See https://doc.rust-lang.org/src/alloc/vec.rs.html#1335-1337.)
1 parent 52f6286 commit 4a58e19

File tree

1 file changed

+7
-9
lines changed

1 file changed

+7
-9
lines changed

src/combinations.rs

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ use super::lazy_buffer::LazyBuffer;
77
/// See [`.combinations()`](../trait.Itertools.html#method.combinations) for more information.
88
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
99
pub struct Combinations<I: Iterator> {
10-
k: usize,
1110
indices: Vec<usize>,
1211
pool: LazyBuffer<I>,
1312
first: bool,
@@ -17,14 +16,14 @@ impl<I> Clone for Combinations<I>
1716
where I: Clone + Iterator,
1817
I::Item: Clone,
1918
{
20-
clone_fields!(k, indices, pool, first);
19+
clone_fields!(indices, pool, first);
2120
}
2221

2322
impl<I> fmt::Debug for Combinations<I>
2423
where I: Iterator + fmt::Debug,
2524
I::Item: fmt::Debug,
2625
{
27-
debug_fmt_fields!(Combinations, k, indices, pool, first);
26+
debug_fmt_fields!(Combinations, indices, pool, first);
2827
}
2928

3029
/// Create a new `Combinations` from a clonable iterator.
@@ -40,7 +39,6 @@ pub fn combinations<I>(iter: I, k: usize) -> Combinations<I>
4039
}
4140

4241
Combinations {
43-
k: k,
4442
indices: (0..k).collect(),
4543
pool: pool,
4644
first: true,
@@ -60,11 +58,11 @@ impl<I> Iterator for Combinations<I>
6058
return None;
6159
}
6260
self.first = false;
63-
} else if self.k == 0 {
61+
} else if self.indices.len() == 0 {
6462
return None;
6563
} else {
6664
// Scan from the end, looking for an index to increment
67-
let mut i: usize = self.k - 1;
65+
let mut i: usize = self.indices.len() - 1;
6866

6967
// Check if we need to consume more from the iterator
7068
if self.indices[i] == pool_len - 1 && !self.pool.is_done() {
@@ -73,7 +71,7 @@ impl<I> Iterator for Combinations<I>
7371
}
7472
}
7573

76-
while self.indices[i] == i + pool_len - self.k {
74+
while self.indices[i] == i + pool_len - self.indices.len() {
7775
if i > 0 {
7876
i -= 1;
7977
} else {
@@ -85,14 +83,14 @@ impl<I> Iterator for Combinations<I>
8583
// Increment index, and reset the ones to its right
8684
self.indices[i] += 1;
8785
let mut j = i + 1;
88-
while j < self.k {
86+
while j < self.indices.len() {
8987
self.indices[j] = self.indices[j - 1] + 1;
9088
j += 1;
9189
}
9290
}
9391

9492
// Create result vector based on the indices
95-
let mut result = Vec::with_capacity(self.k);
93+
let mut result = Vec::with_capacity(self.indices.len());
9694
for i in self.indices.iter() {
9795
result.push(self.pool[*i].clone());
9896
}

0 commit comments

Comments
 (0)