Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify CombinationsWithReplacement #487

Merged
merged 2 commits into from
Oct 10, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 4 additions & 11 deletions src/combinations_with_replacement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,7 @@ where
I: Iterator,
I::Item: Clone,
{
k: usize,
indices: Vec<usize>,
// The current known max index value. This increases as pool grows.
max_index: usize,
pool: LazyBuffer<I>,
first: bool,
}
Expand All @@ -25,7 +22,7 @@ where
I: Iterator + fmt::Debug,
I::Item: fmt::Debug + Clone,
{
debug_fmt_fields!(Combinations, k, indices, max_index, pool, first);
debug_fmt_fields!(Combinations, indices, pool, first);
}

impl<I> CombinationsWithReplacement<I>
Expand All @@ -49,9 +46,7 @@ where
let pool: LazyBuffer<I> = LazyBuffer::new(iter);

CombinationsWithReplacement {
k,
indices,
max_index: 0,
pool,
first: true,
}
Expand All @@ -67,7 +62,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.get_next() {
return if self.indices.len() != 0 && !self.pool.get_next() {
None
// Otherwise, yield the initial state
} else {
Expand All @@ -78,14 +73,12 @@ where

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

// Work out where we need to update our indices
let mut increment: Option<(usize, usize)> = None;
for (i, indices_int) in self.indices.iter().enumerate().rev() {
if indices_int < &self.max_index {
if *indices_int < self.pool.len()-1 {
increment = Some((i, indices_int + 1));
break;
}
Expand Down