1use core::array;
2use core::borrow::BorrowMut;
3use std::fmt;
4use std::iter::FusedIterator;
56use super::lazy_buffer::LazyBuffer;
7use alloc::vec::Vec;
89use crate::adaptors::checked_binomial;
1011/// Iterator for `Vec` valued combinations returned by [`.combinations()`](crate::Itertools::combinations)
12pub type Combinations<I> = CombinationsGeneric<I, Vec<usize>>;
13/// Iterator for const generic combinations returned by [`.array_combinations()`](crate::Itertools::array_combinations)
14pub type ArrayCombinations<I, const K: usize> = CombinationsGeneric<I, [usize; K]>;
1516/// Create a new `Combinations` from a clonable iterator.
17pub fn combinations<I: Iterator>(iter: I, k: usize) -> Combinations<I>
18where
19I::Item: Clone,
20{
21 Combinations::new(iter, (0..k).collect())
22}
2324/// Create a new `ArrayCombinations` from a clonable iterator.
25pub fn array_combinations<I: Iterator, const K: usize>(iter: I) -> ArrayCombinations<I, K>
26where
27I::Item: Clone,
28{
29 ArrayCombinations::new(iter, array::from_fn(|i| i))
30}
3132/// An iterator to iterate through all the `k`-length combinations in an iterator.
33///
34/// See [`.combinations()`](crate::Itertools::combinations) and [`.array_combinations()`](crate::Itertools::array_combinations) for more information.
35#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
36pub struct CombinationsGeneric<I: Iterator, Idx> {
37 indices: Idx,
38 pool: LazyBuffer<I>,
39 first: bool,
40}
4142/// A type holding indices of elements in a pool or buffer of items from an inner iterator
43/// and used to pick out different combinations in a generic way.
44pub trait PoolIndex<T>: BorrowMut<[usize]> {
45type Item;
4647fn extract_item<I: Iterator<Item = T>>(&self, pool: &LazyBuffer<I>) -> Self::Item
48where
49T: Clone;
5051fn len(&self) -> usize {
52self.borrow().len()
53 }
54}
5556impl<T> PoolIndex<T> for Vec<usize> {
57type Item = Vec<T>;
5859fn extract_item<I: Iterator<Item = T>>(&self, pool: &LazyBuffer<I>) -> Vec<T>
60where
61T: Clone,
62 {
63 pool.get_at(self)
64 }
65}
6667impl<T, const K: usize> PoolIndex<T> for [usize; K] {
68type Item = [T; K];
6970fn extract_item<I: Iterator<Item = T>>(&self, pool: &LazyBuffer<I>) -> [T; K]
71where
72T: Clone,
73 {
74 pool.get_array(*self)
75 }
76}
7778impl<I, Idx> Clone for CombinationsGeneric<I, Idx>
79where
80I: Iterator + Clone,
81 I::Item: Clone,
82 Idx: Clone,
83{
84clone_fields!(indices, pool, first);
85}
8687impl<I, Idx> fmt::Debug for CombinationsGeneric<I, Idx>
88where
89I: Iterator + fmt::Debug,
90 I::Item: fmt::Debug,
91 Idx: fmt::Debug,
92{
93debug_fmt_fields!(Combinations, indices, pool, first);
94}
9596impl<I: Iterator, Idx: PoolIndex<I::Item>> CombinationsGeneric<I, Idx> {
97/// Constructor with arguments the inner iterator and the initial state for the indices.
98fn new(iter: I, indices: Idx) -> Self {
99Self {
100 indices,
101 pool: LazyBuffer::new(iter),
102 first: true,
103 }
104 }
105106/// Returns the length of a combination produced by this iterator.
107#[inline]
108pub fn k(&self) -> usize {
109self.indices.len()
110 }
111112/// Returns the (current) length of the pool from which combination elements are
113 /// selected. This value can change between invocations of [`next`](Combinations::next).
114#[inline]
115pub fn n(&self) -> usize {
116self.pool.len()
117 }
118119/// Returns a reference to the source pool.
120#[inline]
121pub(crate) fn src(&self) -> &LazyBuffer<I> {
122&self.pool
123 }
124125/// Return the length of the inner iterator and the count of remaining combinations.
126pub(crate) fn n_and_count(self) -> (usize, usize) {
127let Self {
128 indices,
129 pool,
130 first,
131 } = self;
132let n = pool.count();
133 (n, remaining_for(n, first, indices.borrow()).unwrap())
134 }
135136/// Initialises the iterator by filling a buffer with elements from the
137 /// iterator. Returns true if there are no combinations, false otherwise.
138fn init(&mut self) -> bool {
139self.pool.prefill(self.k());
140let done = self.k() > self.n();
141if !done {
142self.first = false;
143 }
144145 done
146 }
147148/// Increments indices representing the combination to advance to the next
149 /// (in lexicographic order by increasing sequence) combination. For example
150 /// if we have n=4 & k=2 then `[0, 1] -> [0, 2] -> [0, 3] -> [1, 2] -> ...`
151 ///
152 /// Returns true if we've run out of combinations, false otherwise.
153fn increment_indices(&mut self) -> bool {
154// Borrow once instead of noise each time it's indexed
155let indices = self.indices.borrow_mut();
156157if indices.is_empty() {
158return true; // Done
159}
160// Scan from the end, looking for an index to increment
161let mut i: usize = indices.len() - 1;
162163// Check if we need to consume more from the iterator
164if indices[i] == self.pool.len() - 1 {
165self.pool.get_next(); // may change pool size
166}
167168while indices[i] == i + self.pool.len() - indices.len() {
169if i > 0 {
170 i -= 1;
171 } else {
172// Reached the last combination
173return true;
174 }
175 }
176177// Increment index, and reset the ones to its right
178indices[i] += 1;
179for j in i + 1..indices.len() {
180 indices[j] = indices[j - 1] + 1;
181 }
182// If we've made it this far, we haven't run out of combos
183false
184}
185186/// Returns the n-th item or the number of successful steps.
187pub(crate) fn try_nth(&mut self, n: usize) -> Result<<Self as Iterator>::Item, usize>
188where
189I: Iterator,
190 I::Item: Clone,
191 {
192let done = if self.first {
193self.init()
194 } else {
195self.increment_indices()
196 };
197if done {
198return Err(0);
199 }
200for i in 0..n {
201if self.increment_indices() {
202return Err(i + 1);
203 }
204 }
205Ok(self.indices.extract_item(&self.pool))
206 }
207}
208209impl<I, Idx> Iterator for CombinationsGeneric<I, Idx>
210where
211I: Iterator,
212 I::Item: Clone,
213 Idx: PoolIndex<I::Item>,
214{
215type Item = Idx::Item;
216fn next(&mut self) -> Option<Self::Item> {
217let done = if self.first {
218self.init()
219 } else {
220self.increment_indices()
221 };
222223if done {
224return None;
225 }
226227Some(self.indices.extract_item(&self.pool))
228 }
229230fn nth(&mut self, n: usize) -> Option<Self::Item> {
231self.try_nth(n).ok()
232 }
233234fn size_hint(&self) -> (usize, Option<usize>) {
235let (mut low, mut upp) = self.pool.size_hint();
236 low = remaining_for(low, self.first, self.indices.borrow()).unwrap_or(usize::MAX);
237 upp = upp.and_then(|upp| remaining_for(upp, self.first, self.indices.borrow()));
238 (low, upp)
239 }
240241#[inline]
242fn count(self) -> usize {
243self.n_and_count().1
244}
245}
246247impl<I, Idx> FusedIterator for CombinationsGeneric<I, Idx>
248where
249I: Iterator,
250 I::Item: Clone,
251 Idx: PoolIndex<I::Item>,
252{
253}
254255impl<I: Iterator> Combinations<I> {
256/// Resets this `Combinations` back to an initial state for combinations of length
257 /// `k` over the same pool data source. If `k` is larger than the current length
258 /// of the data pool an attempt is made to prefill the pool so that it holds `k`
259 /// elements.
260pub(crate) fn reset(&mut self, k: usize) {
261self.first = true;
262263if k < self.indices.len() {
264self.indices.truncate(k);
265for i in 0..k {
266self.indices[i] = i;
267 }
268 } else {
269for i in 0..self.indices.len() {
270self.indices[i] = i;
271 }
272self.indices.extend(self.indices.len()..k);
273self.pool.prefill(k);
274 }
275 }
276}
277278/// For a given size `n`, return the count of remaining combinations or None if it would overflow.
279fn remaining_for(n: usize, first: bool, indices: &[usize]) -> Option<usize> {
280let k = indices.len();
281if n < k {
282Some(0)
283 } else if first {
284 checked_binomial(n, k)
285 } else {
286// https://en.wikipedia.org/wiki/Combinatorial_number_system
287 // http://www.site.uottawa.ca/~lucia/courses/5165-09/GenCombObj.pdf
288289 // The combinations generated after the current one can be counted by counting as follows:
290 // - The subsequent combinations that differ in indices[0]:
291 // If subsequent combinations differ in indices[0], then their value for indices[0]
292 // must be at least 1 greater than the current indices[0].
293 // As indices is strictly monotonically sorted, this means we can effectively choose k values
294 // from (n - 1 - indices[0]), leading to binomial(n - 1 - indices[0], k) possibilities.
295 // - The subsequent combinations with same indices[0], but differing indices[1]:
296 // Here we can choose k - 1 values from (n - 1 - indices[1]) values,
297 // leading to binomial(n - 1 - indices[1], k - 1) possibilities.
298 // - (...)
299 // - The subsequent combinations with same indices[0..=i], but differing indices[i]:
300 // Here we can choose k - i values from (n - 1 - indices[i]) values: binomial(n - 1 - indices[i], k - i).
301 // Since subsequent combinations can in any index, we must sum up the aforementioned binomial coefficients.
302303 // Below, `n0` resembles indices[i].
304indices.iter().enumerate().try_fold(0usize, |sum, (i, n0)| {
305 sum.checked_add(checked_binomial(n - 1 - *n0, k - i)?)
306 })
307 }
308}