Skip to content

Commit 21907bd

Browse files
CombinationsWithReplacement::increment_indices
Steal how `next` increment indices, a bit improved. It will soon be used in `nth` (and more later).
1 parent 2f53aea commit 21907bd

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

src/combinations_with_replacement.rs

+40
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,46 @@ where
4646
}
4747
}
4848

49+
impl<I> CombinationsWithReplacement<I>
50+
where
51+
I: Iterator,
52+
I::Item: Clone,
53+
{
54+
/// Increments indices representing the combination to advance to the next
55+
/// (in lexicographic order by increasing sequence) combination.
56+
///
57+
/// Returns true if we've run out of combinations, false otherwise.
58+
fn increment_indices(&mut self) -> bool {
59+
// Check if we need to consume more from the iterator
60+
// This will run while we increment our first index digit
61+
self.pool.get_next();
62+
63+
// Work out where we need to update our indices
64+
let mut increment = None;
65+
for (i, indices_int) in self.indices.iter().enumerate().rev() {
66+
if *indices_int < self.pool.len() - 1 {
67+
increment = Some((i, indices_int + 1));
68+
break;
69+
}
70+
}
71+
match increment {
72+
// If we can update the indices further
73+
Some((increment_from, increment_value)) => {
74+
// We need to update the rightmost non-max value
75+
// and all those to the right
76+
for i in &mut self.indices[increment_from..] {
77+
*i = increment_value;
78+
}
79+
// TODO: once MSRV >= 1.50, use `fill` instead:
80+
// self.indices[increment_from..].fill(increment_value);
81+
false
82+
}
83+
// Otherwise, we're done
84+
None => true,
85+
}
86+
}
87+
}
88+
4989
impl<I> Iterator for CombinationsWithReplacement<I>
5090
where
5191
I: Iterator,

0 commit comments

Comments
 (0)