Skip to content

Commit

Permalink
Merge #383
Browse files Browse the repository at this point in the history
383: Fix combinations(0) and combinations_with_replacement(0). r=jswrenn a=andersk

The empty combination is always a valid combination of length 0.

Fixes #361 while also simplifying the code.

Co-authored-by: Anders Kaseorg <andersk@mit.edu>
  • Loading branch information
bors[bot] and andersk committed Jan 14, 2020
2 parents 16d9f5f + 13aa10e commit bfbe01d
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 20 deletions.
8 changes: 3 additions & 5 deletions src/combinations.rs
Expand Up @@ -65,13 +65,11 @@ impl<I> Iterator for Combinations<I>
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 {
if self.pool.is_done() {
return None;
}
self.first = false;
} else if self.k == 0 {
return None;
Expand Down
5 changes: 2 additions & 3 deletions src/combinations_with_replacement.rs
Expand Up @@ -66,7 +66,7 @@ where
// If this is the first iteration, return early
if self.first {
// In empty edge cases, stop iterating immediately
return if self.k == 0 || self.pool.is_done() {
return if self.k != 0 && !self.pool.get_next() {
None
// Otherwise, yield the initial state
} else {
Expand All @@ -77,8 +77,7 @@ where

// Check if we need to consume more from the iterator
// This will run while we increment our first index digit
if !self.pool.is_done() {
self.pool.get_next();
if self.pool.get_next() {
self.max_index = self.pool.len() - 1;
}

Expand Down
13 changes: 2 additions & 11 deletions src/lazy_buffer.rs
Expand Up @@ -12,19 +12,10 @@ where
I: Iterator,
{
pub fn new(it: I) -> LazyBuffer<I> {
let mut it = it;
let mut buffer = Vec::new();
let done;
if let Some(first) = it.next() {
buffer.push(first);
done = false;
} else {
done = true;
}
LazyBuffer {
it: it,
done: done,
buffer: buffer,
done: false,
buffer: Vec::new(),
}
}

Expand Down
14 changes: 13 additions & 1 deletion tests/test_std.rs
Expand Up @@ -599,6 +599,13 @@ fn combinations_of_too_short() {
#[test]
fn combinations_zero() {
it::assert_equal((1..3).combinations(0), vec![vec![]]);
it::assert_equal((0..0).combinations(0), vec![vec![]]);
}

#[test]
fn permutations_zero() {
it::assert_equal((1..3).permutations(0), vec![vec![]]);
it::assert_equal((0..0).permutations(0), vec![vec![]]);
}

#[test]
Expand All @@ -620,7 +627,12 @@ fn combinations_with_replacement() {
// Zero size
it::assert_equal(
(0..3).combinations_with_replacement(0),
<Vec<Vec<_>>>::new(),
vec![vec![]],
);
// Zero size on empty pool
it::assert_equal(
(0..0).combinations_with_replacement(0),
vec![vec![]],
);
// Empty pool
it::assert_equal(
Expand Down

0 comments on commit bfbe01d

Please sign in to comment.