malachite_base/vecs/
exhaustive.rs

1// Copyright © 2025 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9use crate::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
10use crate::iterators::iterator_cache::IteratorCache;
11use crate::num::arithmetic::traits::CheckedPow;
12use crate::num::conversion::traits::{ExactFrom, SaturatingFrom, WrappingFrom};
13use crate::num::exhaustive::{
14    PrimitiveIntIncreasingRange, exhaustive_unsigneds, primitive_int_increasing_inclusive_range,
15    primitive_int_increasing_range,
16};
17use crate::num::iterators::{RulerSequence, ruler_sequence};
18use crate::num::logic::traits::SignificantBits;
19use crate::tuples::exhaustive::{
20    ExhaustiveDependentPairs, ExhaustiveDependentPairsYsGenerator, LexDependentPairs,
21    exhaustive_dependent_pairs, exhaustive_dependent_pairs_stop_after_empty_ys,
22    lex_dependent_pairs_stop_after_empty_ys,
23};
24use crate::vecs::{ExhaustiveVecPermutations, exhaustive_vec_permutations};
25use alloc::vec;
26use alloc::vec::Vec;
27use core::cmp::{
28    Ordering::{self, *},
29    max, min,
30};
31use core::iter::{FromIterator, Once, Zip, empty, once};
32use core::marker::PhantomData;
33use core::mem::take;
34use core::ops::RangeFrom;
35use itertools::{Itertools, repeat_n};
36
37#[doc(hidden)]
38pub fn validate_oi_map<I: Iterator<Item = usize>>(max_input_index: usize, xs: I) {
39    let mut oi_unique = hashbrown::HashSet::new();
40    oi_unique.extend(xs);
41    let oi_sorted_unique = oi_unique.into_iter().sorted().collect_vec();
42    assert_eq!(oi_sorted_unique.len(), max_input_index + 1);
43    assert_eq!(*oi_sorted_unique.first().unwrap(), 0);
44    assert_eq!(*oi_sorted_unique.last().unwrap(), max_input_index);
45}
46
47#[doc(hidden)]
48#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
49pub struct LexFixedLengthVecsOutput {
50    pub input_index: usize,
51    pub counter: usize,
52}
53
54/// Defines lexicographic fixed-length [`Vec`] generators.
55///
56/// Malachite provides [`lex_vecs_length_2`] and [`lex_vecs_fixed_length_2_inputs`], but you can
57/// also define `lex_vecs_length_3`, `lex_vecs_length_4`, and so on, and
58/// `lex_vecs_fixed_length_3_inputs`, `lex_vecs_fixed_length_4_inputs`, and so on, in your program
59/// using the code below. The documentation for [`lex_vecs_length_2`] and
60/// [`lex_vecs_fixed_length_2_inputs`] describes these other functions as well.
61///
62/// See usage examples [here](self#lex_vecs_length_2) and
63/// [here](self#lex_vecs_fixed_length_2_inputs).
64///
65/// ```
66/// use malachite_base::iterators::iterator_cache::IteratorCache;
67/// use malachite_base::lex_vecs_fixed_length;
68/// use malachite_base::vecs::exhaustive::{validate_oi_map, LexFixedLengthVecsOutput};
69///
70/// lex_vecs_fixed_length!(
71///     (pub(crate)),
72///     LexFixedLengthVecs3Inputs,
73///     lex_vecs_fixed_length_3_inputs,
74///     lex_vecs_length_3,
75///     [0, I, xs, xs_outputs],
76///     [1, J, ys, ys_outputs],
77///     [2, K, zs, zs_outputs]
78/// );
79/// lex_vecs_fixed_length!(
80///     (pub(crate)),
81///     LexFixedLengthVecs4Inputs,
82///     lex_vecs_fixed_length_4_inputs,
83///     lex_vecs_length_4,
84///     [0, I, xs, xs_outputs],
85///     [1, J, ys, ys_outputs],
86///     [2, K, zs, zs_outputs],
87///     [3, L, ws, ws_outputs]
88/// );
89/// lex_vecs_fixed_length!(
90///     (pub(crate)),
91///     LexFixedLengthVecs5Inputs,
92///     lex_vecs_fixed_length_5_inputs,
93///     lex_vecs_length_5,
94///     [0, I, xs, xs_outputs],
95///     [1, J, ys, ys_outputs],
96///     [2, K, zs, zs_outputs],
97///     [3, L, ws, ws_outputs],
98///     [4, M, vs, vs_outputs]
99/// );
100/// lex_vecs_fixed_length!(
101///     (pub(crate)),
102///     LexFixedLengthVecs6Inputs,
103///     lex_vecs_fixed_length_6_inputs,
104///     lex_vecs_length_6,
105///     [0, I, xs, xs_outputs],
106///     [1, J, ys, ys_outputs],
107///     [2, K, zs, zs_outputs],
108///     [3, L, ws, ws_outputs],
109///     [4, M, vs, vs_outputs],
110///     [5, N, us, us_outputs]
111/// );
112/// lex_vecs_fixed_length!(
113///     (pub(crate)),
114///     LexFixedLengthVecs7Inputs,
115///     lex_vecs_fixed_length_7_inputs,
116///     lex_vecs_length_7,
117///     [0, I, xs, xs_outputs],
118///     [1, J, ys, ys_outputs],
119///     [2, K, zs, zs_outputs],
120///     [3, L, ws, ws_outputs],
121///     [4, M, vs, vs_outputs],
122///     [5, N, us, us_outputs],
123///     [6, O, ts, ts_outputs]
124/// );
125/// lex_vecs_fixed_length!(
126///     (pub(crate)),
127///     LexFixedLengthVecs8Inputs,
128///     lex_vecs_fixed_length_8_inputs,
129///     lex_vecs_length_8,
130///     [0, I, xs, xs_outputs],
131///     [1, J, ys, ys_outputs],
132///     [2, K, zs, zs_outputs],
133///     [3, L, ws, ws_outputs],
134///     [4, M, vs, vs_outputs],
135///     [5, N, us, us_outputs],
136///     [6, O, ts, ts_outputs],
137///     [7, P, ss, ss_outputs]
138/// );
139/// ```
140#[macro_export]
141macro_rules! lex_vecs_fixed_length {
142    (
143        ($($vis:tt)*),
144        $exhaustive_struct: ident,
145        $exhaustive_custom_fn: ident,
146        $exhaustive_1_to_1_fn: ident,
147        $([$i: expr, $it: ident, $xs: ident, $xs_outputs: ident]),*
148    ) => {
149        /// This documentation applies not only to `LexFixedLengthVecs2Inputs`, but also to
150        /// `LexFixedLengthVecs3Inputs`, `LexFixedLengthVecs4Inputs`, and so on. See
151        /// [`lex_vecs_fixed_length`] for more information.
152        ///
153        /// Generates all [`Vec`]s of a given length with elements from $m$ iterators, in
154        /// lexicographic order.
155        ///
156        /// The order is lexicographic with respect to the order of the element iterators.
157        ///
158        /// The fixed length $n$ of the [`Vec`]s is greater than or equal to $m$.
159        #[derive(Clone, Debug)]
160        $($vis)* struct $exhaustive_struct<T: Clone, $($it: Iterator<Item = T>,)*> {
161            first: bool,
162            done: bool,
163            $(
164                $xs: IteratorCache<$it>,
165                $xs_outputs: Vec<usize>,
166            )*
167            outputs: Vec<LexFixedLengthVecsOutput>,
168        }
169
170        impl<T: Clone, $($it: Iterator<Item = T>,)*> $exhaustive_struct<T, $($it,)*> {
171            fn increment_counters(&mut self) -> bool {
172                for (i, output) in self.outputs.iter_mut().enumerate().rev() {
173                    output.counter += 1;
174                    let no_carry = match output.input_index {
175                        $(
176                            $i => self.$xs.get(output.counter).is_some(),
177                        )*
178                        _ => unreachable!(),
179                    };
180                    if no_carry {
181                        return false;
182                    } else if i == 0 {
183                        return true;
184                    }
185                    output.counter = 0;
186                }
187                false
188            }
189        }
190
191        impl<T: Clone, $($it: Iterator<Item = T>,)*> Iterator for $exhaustive_struct<T, $($it,)*>
192        {
193            type Item = Vec<T>;
194
195            fn next(&mut self) -> Option<Vec<T>> {
196                if self.done {
197                    None
198                } else if self.first {
199                    self.first = false;
200                    let mut next = vec![None; self.outputs.len()];
201                    $(
202                        if let Some(x) = self.$xs.get(0) {
203                            for &output_index in &self.$xs_outputs {
204                                next[output_index] = Some(x.clone());
205                            }
206                        } else {
207                            self.done = true;
208                            return None;
209                        }
210                    )*
211                    Some(next.into_iter().map(Option::unwrap).collect())
212                } else {
213                    if self.increment_counters() {
214                        self.done = true;
215                        return None;
216                    }
217                    let mut next = Vec::with_capacity(self.outputs.len());
218                    for &output in &self.outputs {
219                        let x = match output.input_index {
220                            $(
221                                $i => self.$xs.get(output.counter),
222                            )*
223                            _ => unreachable!(),
224                        };
225                        next.push(x.unwrap().clone());
226                    }
227                    Some(next)
228                }
229            }
230        }
231
232        /// This documentation applies not only to `lex_vecs_fixed_length_2_inputs`, but also to
233        /// `lex_vecs_fixed_length_3_inputs`, `lex_vecs_fixed_length_4_inputs`, and so on. See
234        /// [`lex_vecs_fixed_length`] for more information.
235        ///
236        /// Generates all length-$n$ [`Vec`]s with elements from $m$ iterators, where $m \leq n$, in
237        /// lexicographic order.
238        ///
239        /// The order is lexicographic with respect to the order of the element iterators.
240        ///
241        /// The `output_to_input_map` parameter defines which iterators are mapped to which slot in
242        /// the output [`Vec`]s. The length of the output [`Vec`]s, $n$, is specified by the length
243        /// of `output_to_input_map`.
244        ///
245        /// The $i$th element of `output_to_input_map` is an index from 0 to $m-1$ which specifies
246        /// which iterator the $i$th output slot is populated with. Together, the elements must
247        /// include all indices from 0 to $m-1$, inclusive, possibly with repetitions.
248        ///
249        /// Let `xs` be the input iterator mapped to the first slot of the output [`Vec`]s. All the
250        /// input iterators, except possibly `xs`, must be finite. If `xs` is finite, the output
251        /// length is the product of the lengths of all the input iterators. If `xs` is infinite,
252        /// the output is also infinite.
253        ///
254        /// If any of the input iterators is empty, the output is also empty.
255        ///
256        /// # Examples
257        /// See [here](self#lex_vecs_fixed_length_2_inputs).
258        #[allow(dead_code)]
259        $($vis)* fn $exhaustive_custom_fn<T: Clone, $($it: Iterator<Item = T>,)*>(
260            $($xs: $it,)*
261            output_to_input_map: &[usize],
262        ) -> $exhaustive_struct<T, $($it,)*> {
263            $(
264                let _max_input_index = $i;
265            )*
266            validate_oi_map(_max_input_index, output_to_input_map.iter().cloned());
267            $(
268                let $xs_outputs = output_to_input_map
269                    .iter()
270                    .enumerate()
271                    .filter_map(|(o, i)| if *i == $i { Some(o) } else { None })
272                    .collect();
273            )*
274            $exhaustive_struct {
275                first: true,
276                done: false,
277                $(
278                    $xs: IteratorCache::new($xs),
279                    $xs_outputs,
280                )*
281                outputs: output_to_input_map
282                    .iter()
283                    .map(|&i| LexFixedLengthVecsOutput {
284                        input_index: i,
285                        counter: 0,
286                    })
287                    .collect(),
288            }
289        }
290
291        /// This documentation applies not only to `lex_vecs_length_2`, but also to
292        /// `lex_vecs_length_3`, `lex_vecs_length_4`, and so on. See [`lex_vecs_fixed_length`] for
293        /// more information.
294        ///
295        /// Generates all length-$n$ [`Vec`]s with elements from $n$ iterators, in lexicographic
296        /// order.
297        ///
298        /// The order is lexicographic with respect to the order of the element iterators.
299        ///
300        /// All of `ys`, `zs`, ... (but not necessarily `xs`) must be finite. If `xs` is finite, the
301        /// output length is the product of the lengths of all the input iterators. If `xs` is
302        /// infinite, the output is also infinite.
303        ///
304        /// If any of `xs`, `ys`, `zs`, ... is empty, the output is also empty.
305        ///
306        /// # Examples
307        /// See [here](self#lex_vecs_length_2).
308        #[allow(dead_code)]
309        #[inline]
310        $($vis)* fn $exhaustive_1_to_1_fn<T: Clone, $($it: Iterator<Item = T>,)*>(
311            $($xs: $it,)*
312        ) -> $exhaustive_struct<T, $($it,)*> {
313            $exhaustive_custom_fn($($xs,)* &[$($i,)*])
314        }
315    }
316}
317
318lex_vecs_fixed_length!(
319    (pub),
320    LexFixedLengthVecs2Inputs,
321    lex_vecs_fixed_length_2_inputs,
322    lex_vecs_length_2,
323    [0, I, xs, xs_outputs],
324    [1, J, ys, ys_outputs]
325);
326
327#[doc(hidden)]
328#[derive(Clone, Debug)]
329pub struct LexFixedLengthVecsFromSingleG<I: Iterator>
330where
331    I::Item: Clone,
332{
333    first: bool,
334    done: bool,
335    xs: IteratorCache<I>,
336    counters: Vec<usize>,
337    phantom: PhantomData<*const I::Item>,
338}
339
340impl<I: Iterator> LexFixedLengthVecsFromSingleG<I>
341where
342    I::Item: Clone,
343{
344    fn increment_counters(&mut self) -> bool {
345        for (i, counter) in self.counters.iter_mut().enumerate().rev() {
346            *counter += 1;
347            if self.xs.get(*counter).is_some() {
348                return false;
349            } else if i == 0 {
350                return true;
351            }
352            *counter = 0;
353        }
354        false
355    }
356}
357
358impl<I: Iterator> Iterator for LexFixedLengthVecsFromSingleG<I>
359where
360    I::Item: Clone,
361{
362    type Item = Vec<I::Item>;
363
364    fn next(&mut self) -> Option<Vec<I::Item>> {
365        if self.done {
366            None
367        } else if self.first {
368            self.first = false;
369            if let Some(x) = self.xs.get(0) {
370                Some(repeat_n(x, self.counters.len()).cloned().collect())
371            } else {
372                self.done = true;
373                None
374            }
375        } else if self.increment_counters() {
376            self.done = true;
377            None
378        } else {
379            let xs = &mut self.xs;
380            Some(
381                self.counters
382                    .iter()
383                    .map(|&c| xs.get(c).unwrap().clone())
384                    .collect(),
385            )
386        }
387    }
388}
389
390fn lex_vecs_fixed_length_from_single_g<I: Iterator>(
391    len: u64,
392    xs: I,
393) -> LexFixedLengthVecsFromSingleG<I>
394where
395    I::Item: Clone,
396{
397    LexFixedLengthVecsFromSingleG {
398        first: true,
399        done: false,
400        xs: IteratorCache::new(xs),
401        counters: vec![0; usize::exact_from(len)],
402        phantom: PhantomData,
403    }
404}
405
406/// Generates all [`Vec`]s of a given length with elements from a single iterator, in lexicographic
407/// order.
408///
409/// The order is lexicographic with respect to the order of the element iterator.
410///
411/// This `struct` is created by the [`lex_vecs_fixed_length_from_single`]; see its documentation for
412/// more.
413#[derive(Clone, Debug)]
414pub enum LexFixedLengthVecsFromSingle<I: Iterator>
415where
416    I::Item: Clone,
417{
418    Zero(Once<Vec<I::Item>>),
419    One(I),
420    GreaterThanOne(LexFixedLengthVecsFromSingleG<I>),
421}
422
423impl<I: Iterator> Iterator for LexFixedLengthVecsFromSingle<I>
424where
425    I::Item: Clone,
426{
427    type Item = Vec<I::Item>;
428
429    fn next(&mut self) -> Option<Vec<I::Item>> {
430        match self {
431            LexFixedLengthVecsFromSingle::Zero(xs) => xs.next(),
432            LexFixedLengthVecsFromSingle::One(xs) => xs.next().map(|x| vec![x]),
433            LexFixedLengthVecsFromSingle::GreaterThanOne(xs) => xs.next(),
434        }
435    }
436}
437
438/// Generates all [`Vec`]s of a given length with elements from a single iterator, in lexicographic
439/// order.
440///
441/// The order is lexicographic with respect to the order of the element iterator.
442///
443/// `xs` must be finite.
444///
445/// The output length is $k^n$, where $k$ is `xs.count()` and $n$ is `len`.
446///
447/// If `len` is 0, the output consists of one empty [`Vec`].
448///
449/// If `xs` is empty, the output is also empty, unless `len` is 0.
450///
451/// # Examples
452/// ```
453/// use itertools::Itertools;
454/// use malachite_base::vecs::exhaustive::lex_vecs_fixed_length_from_single;
455///
456/// let xss = lex_vecs_fixed_length_from_single(2, 0..4).collect_vec();
457/// assert_eq!(
458///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
459///     &[
460///         &[0, 0],
461///         &[0, 1],
462///         &[0, 2],
463///         &[0, 3],
464///         &[1, 0],
465///         &[1, 1],
466///         &[1, 2],
467///         &[1, 3],
468///         &[2, 0],
469///         &[2, 1],
470///         &[2, 2],
471///         &[2, 3],
472///         &[3, 0],
473///         &[3, 1],
474///         &[3, 2],
475///         &[3, 3]
476///     ]
477/// );
478/// ```
479pub fn lex_vecs_fixed_length_from_single<I: Iterator>(
480    len: u64,
481    xs: I,
482) -> LexFixedLengthVecsFromSingle<I>
483where
484    I::Item: Clone,
485{
486    match len {
487        0 => LexFixedLengthVecsFromSingle::Zero(once(Vec::new())),
488        1 => LexFixedLengthVecsFromSingle::One(xs),
489        len => LexFixedLengthVecsFromSingle::GreaterThanOne(lex_vecs_fixed_length_from_single_g(
490            len, xs,
491        )),
492    }
493}
494
495/// Defines exhaustive fixed-length [`Vec`] generators.
496///
497/// Malachite provides [`exhaustive_vecs_length_2`] and [`exhaustive_vecs_fixed_length_2_inputs`],
498/// but you can also define `exhaustive_vecs_length_3`, `exhaustive_vecs_length_4`, and so on, and
499/// `exhaustive_vecs_fixed_length_3_inputs`, `exhaustive_vecs_fixed_length_4_inputs`, and so on, in
500/// your program using the code below. The documentation for [`exhaustive_vecs_length_2`] and
501/// [`exhaustive_vecs_fixed_length_2_inputs`] describes these other functions as well.
502///
503/// See usage examples [here](self#exhaustive_vecs_length_2) and
504/// [here](self#exhaustive_vecs_fixed_length_2_inputs).
505///
506/// ```
507/// use itertools::Itertools;
508/// use malachite_base::exhaustive_vecs_fixed_length;
509/// use malachite_base::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
510/// use malachite_base::iterators::iterator_cache::IteratorCache;
511/// use malachite_base::num::conversion::traits::{ExactFrom, WrappingFrom};
512/// use malachite_base::num::logic::traits::SignificantBits;
513/// use malachite_base::vecs::exhaustive::validate_oi_map;
514/// use std::cmp::max;
515///
516/// exhaustive_vecs_fixed_length!(
517///     (pub(crate)),
518///     ExhaustiveFixedLengthVecs3Inputs,
519///     exhaustive_vecs_fixed_length_3_inputs,
520///     exhaustive_vecs_length_3,
521///     [0, I, xs, xs_done, xs_outputs],
522///     [1, J, ys, ys_done, ys_outputs],
523///     [2, K, zs, zs_done, zs_outputs]
524/// );
525/// exhaustive_vecs_fixed_length!(
526///     (pub(crate)),
527///     ExhaustiveFixedLengthVecs4Inputs,
528///     exhaustive_vecs_fixed_length_4_inputs,
529///     exhaustive_vecs_length_4,
530///     [0, I, xs, xs_done, xs_outputs],
531///     [1, J, ys, ys_done, ys_outputs],
532///     [2, K, zs, zs_done, zs_outputs],
533///     [3, L, ws, ws_done, ws_outputs]
534/// );
535/// exhaustive_vecs_fixed_length!(
536///     (pub(crate)),
537///     ExhaustiveFixedLengthVecs5Inputs,
538///     exhaustive_vecs_fixed_length_5_inputs,
539///     exhaustive_vecs_length_5,
540///     [0, I, xs, xs_done, xs_outputs],
541///     [1, J, ys, ys_done, ys_outputs],
542///     [2, K, zs, zs_done, zs_outputs],
543///     [3, L, ws, ws_done, ws_outputs],
544///     [4, M, vs, vs_done, vs_outputs]
545/// );
546/// exhaustive_vecs_fixed_length!(
547///     (pub(crate)),
548///     ExhaustiveFixedLengthVecs6Inputs,
549///     exhaustive_vecs_fixed_length_6_inputs,
550///     exhaustive_vecs_length_6,
551///     [0, I, xs, xs_done, xs_outputs],
552///     [1, J, ys, ys_done, ys_outputs],
553///     [2, K, zs, zs_done, zs_outputs],
554///     [3, L, ws, ws_done, ws_outputs],
555///     [4, M, vs, vs_done, vs_outputs],
556///     [5, N, us, us_done, us_outputs]
557/// );
558/// exhaustive_vecs_fixed_length!(
559///     (pub(crate)),
560///     ExhaustiveFixedLengthVecs7,
561///     exhaustive_vecs_fixed_length_7_inputs,
562///     exhaustive_vecs_length_7,
563///     [0, I, xs, xs_done, xs_outputs],
564///     [1, J, ys, ys_done, ys_outputs],
565///     [2, K, zs, zs_done, zs_outputs],
566///     [3, L, ws, ws_done, ws_outputs],
567///     [4, M, vs, vs_done, vs_outputs],
568///     [5, N, us, us_done, us_outputs],
569///     [6, O, ts, ts_done, ts_outputs]
570/// );
571/// exhaustive_vecs_fixed_length!(
572///     (pub(crate)),
573///     ExhaustiveFixedLengthVecs8Inputs,
574///     exhaustive_vecs_fixed_length_8_inputs,
575///     exhaustive_vecs_length_8,
576///     [0, I, xs, xs_done, xs_outputs],
577///     [1, J, ys, ys_done, ys_outputs],
578///     [2, K, zs, zs_done, zs_outputs],
579///     [3, L, ws, ws_done, ws_outputs],
580///     [4, M, vs, vs_done, vs_outputs],
581///     [5, N, us, us_done, us_outputs],
582///     [6, O, ts, ts_done, ts_outputs],
583///     [7, P, ss, ss_done, ss_outputs]
584/// );
585/// ```
586#[macro_export]
587macro_rules! exhaustive_vecs_fixed_length {
588    (
589        ($($vis:tt)*),
590        $exhaustive_struct: ident,
591        $exhaustive_custom_fn: ident,
592        $exhaustive_1_to_1_fn: ident,
593        $([$i: expr, $it: ident, $xs: ident, $xs_done: ident, $outputs: ident]),*
594    ) => {
595        /// This documentation applies not only to `ExhaustiveFixedLengthVecs2Inputs`, but also to
596        /// `ExhaustiveFixedLengthVecs3Inputs`, `ExhaustiveFixedLengthVecs4Inputs`, and so on. See
597        /// [`exhaustive_vecs_fixed_length`] for more information.
598        ///
599        /// Generates all [`Vec`]s of a given length with elements from $m$ iterators.
600        ///
601        /// The fixed length $n$ of the [`Vec`]s is greater than or equal to $m$.
602        #[derive(Clone, Debug)]
603        $($vis)* struct $exhaustive_struct<T: Clone, $($it: Iterator<Item=T>,)*> {
604            i: u64,
605            len: u64,
606            limit: Option<u64>,
607            distributor: BitDistributor,
608            $(
609                $xs: IteratorCache<$it>,
610                $xs_done: bool,
611                $outputs: Vec<usize>,
612            )*
613        }
614
615        impl<T: Clone, $($it: Iterator<Item=T>,)*> $exhaustive_struct<T, $($it,)*> {
616            fn try_getting_limit(&mut self) {
617                let mut all_limits_known = true;
618                $(
619                    if let Some(xs_len) = self.$xs.known_len() {
620                        if xs_len == 0 {
621                            self.limit = Some(0);
622                            return;
623                        }
624                    } else {
625                        all_limits_known = false;
626                    }
627                )*
628                if !all_limits_known {
629                    return;
630                }
631                let mut product = 1u64;
632                $(
633                    let xs_len = u64::exact_from(self.$xs.known_len().unwrap());
634                    for _ in 0..self.$outputs.len() {
635                        if let Some(new_product) = product.checked_mul(xs_len) {
636                            product = new_product;
637                        } else {
638                            return;
639                        }
640                    }
641                )*
642                self.limit = Some(product);
643            }
644        }
645
646        impl<T: Clone, $($it: Iterator<Item=T>,)*> Iterator for $exhaustive_struct<T, $($it,)*> {
647            type Item = Vec<T>;
648
649            fn next(&mut self) -> Option<Vec<T>> {
650                if Some(self.i) == self.limit {
651                    None
652                } else {
653                    if self.i == u64::MAX {
654                        panic!("Too many iterations");
655                    }
656                    loop {
657                        let mut all_are_valid = true;
658                        $(
659                            for &output_index in &self.$outputs {
660                                if self.$xs.get(
661                                    self.distributor.get_output(output_index)
662                                ).is_none() {
663                                    all_are_valid = false;
664                                    break;
665                                }
666                            }
667                            if !all_are_valid {
668                                if self.i == 0 {
669                                    self.limit = Some(0);
670                                    return None;
671                                } else if !self.$xs_done {
672                                    self.try_getting_limit();
673                                    if Some(self.i) == self.limit {
674                                        return None;
675                                    }
676                                    self.$xs_done = true;
677                                    let xs_len = self.$xs.known_len().unwrap();
678                                    // xs_len > 0 at this point
679                                    self.distributor.set_max_bits(
680                                        &self.$outputs,
681                                        max(
682                                            1,
683                                            usize::wrapping_from((xs_len - 1).significant_bits())
684                                        )
685                                    );
686                                } else {
687                                    self.distributor.increment_counter();
688                                }
689                                continue;
690                            }
691                        )*
692                        break;
693                    }
694                    let mut out = vec![None; usize::exact_from(self.len)];
695                    $(
696                        for &output_index in &self.$outputs {
697                            let x = self.$xs.get(self.distributor.get_output(output_index));
698                            out[output_index] = Some(x.unwrap().clone());
699                        }
700                    )*
701                    self.i += 1;
702                    self.distributor.increment_counter();
703                    Some(out.into_iter().map(Option::unwrap).collect())
704                }
705            }
706        }
707
708        /// This documentation applies not only to `exhaustive_vecs_fixed_length_2_inputs`, but also
709        /// to `exhaustive_vecs_fixed_length_3_inputs`, `exhaustive_vecs_fixed_length_4_inputs`, and
710        /// so on. See [`exhaustive_vecs_fixed_length`] for more information.
711        ///
712        /// Generates all [`Vec`]s of a given length with elements from $m$ iterators, where $m \leq
713        /// n$.
714        ///
715        /// The `output_types` parameter defines which iterators are mapped to which slot in the
716        /// output [`Vec`]s, and how quickly each output slot advances through its iterator. The
717        /// length of the output [`Vec`]s, $n$, is specified by the length of `output_types`.
718        ///
719        /// The $i$th element of `output_types` is a pair of [`BitDistributorOutputType`] and
720        /// `usize`. The [`BitDistributorOutputType`] determines how quickly the $i$th output slot
721        /// advances through its iterator; see the [`BitDistributor`] documentation for a
722        /// description of the different types. The `usize` is an index from 0 to $m-1$ which
723        /// specifies which iterator the $i$th output slot is populated with. Together, the `usize`s
724        /// must include all indices from 0 to $m-1$, inclusive, possibly with repetitions.
725        ///
726        /// If all of `xs`, `ys`, `zs`, ... are finite, the output length is the product of their
727        /// lengths. If any of `xs`, `ys`, `zs`, ... are infinite, the output is also infinite.
728        ///
729        /// If any of `xs`, `ys`, `zs`, ... is empty, the output is also empty.
730        ///
731        /// # Panics
732        /// Panics if the `usize`s in `output_types` do not include all indices from 0 to $m-1$,
733        /// inclusive, possibly with repetitions. In particular, the length of `output_types` must
734        /// be at least $m$.
735        ///
736        /// # Examples
737        /// See [here](self#exhaustive_vecs_fixed_length_2_inputs).
738        #[allow(dead_code)]
739        $($vis)* fn $exhaustive_custom_fn<T: Clone, $($it: Iterator<Item=T>,)*> (
740            $($xs: $it,)*
741            output_types: &[(BitDistributorOutputType, usize)],
742        ) -> $exhaustive_struct<T, $($it,)*> {
743            $(
744                let _max_input_index = $i;
745            )*
746            let output_to_input_map = output_types.iter().map(|(_, i)| *i).collect_vec();
747            validate_oi_map(_max_input_index, output_to_input_map.iter().cloned());
748            $exhaustive_struct {
749                i: 0,
750                len: u64::exact_from(output_types.len()),
751                limit: None,
752                distributor: BitDistributor::new(output_types.iter().map(|(ot, _)| *ot)
753                    .collect_vec().as_slice()),
754                $(
755                    $xs: IteratorCache::new($xs),
756                    $xs_done: false,
757                    $outputs: output_types.iter().enumerate()
758                        .filter_map(|(o, (_, i))| if *i == $i { Some(o) } else { None }).collect(),
759                )*
760            }
761        }
762
763        /// This documentation applies not only to `exhaustive_vecs_length_2`, but also to
764        /// `exhaustive_vecs_length_3`, `exhaustive_vecs_length_4`, and so on. See
765        /// [`exhaustive_vecs_fixed_length`] for more information.
766        ///
767        /// Generates all length-$n$ [`Vec`]s with elements from $n$ iterators.
768        ///
769        /// If all of `xs`, `ys`, `zs`, ... are finite, the output length is the product of their
770        /// lengths. If any of `xs`, `ys`, `zs`, ... are infinite, the output is also infinite.
771        ///
772        /// If any of `xs`, `ys`, `zs`, ... is empty, the output is also empty.
773        ///
774        /// # Examples
775        /// See [here](self#exhaustive_vecs_length_2).
776        #[allow(dead_code)]
777        #[inline]
778        $($vis)* fn $exhaustive_1_to_1_fn<T: Clone, $($it: Iterator<Item=T>,)*> (
779            $($xs: $it,)*
780        ) -> $exhaustive_struct<T, $($it,)*> {
781            $exhaustive_custom_fn(
782                $($xs,)*
783                &[$((BitDistributorOutputType::normal(1), $i),)*]
784            )
785        }
786    }
787}
788
789exhaustive_vecs_fixed_length!(
790    (pub),
791    ExhaustiveFixedLengthVecs2Inputs,
792    exhaustive_vecs_fixed_length_2_inputs,
793    exhaustive_vecs_length_2,
794    [0, I, xs, xs_done, xs_outputs],
795    [1, J, ys, ys_done, ys_outputs]
796);
797
798#[doc(hidden)]
799#[derive(Clone, Debug)]
800pub struct ExhaustiveFixedLengthVecs1InputG<I: Iterator>
801where
802    I::Item: Clone,
803{
804    i: u64,
805    len: u64,
806    limit: Option<u64>,
807    distributor: BitDistributor,
808    xs: IteratorCache<I>,
809    xs_done: bool,
810    phantom: PhantomData<*const I::Item>,
811}
812
813impl<I: Iterator> Iterator for ExhaustiveFixedLengthVecs1InputG<I>
814where
815    I::Item: Clone,
816{
817    type Item = Vec<I::Item>;
818
819    fn next(&mut self) -> Option<Vec<I::Item>> {
820        if Some(self.i) == self.limit {
821            None
822        } else {
823            assert!(self.i != u64::MAX, "Too many iterations");
824            loop {
825                let mut all_are_valid = true;
826                for i in 0..usize::exact_from(self.len) {
827                    if self.xs.get(self.distributor.get_output(i)).is_none() {
828                        all_are_valid = false;
829                        break;
830                    }
831                }
832                if all_are_valid {
833                    break;
834                } else if !self.xs_done {
835                    let xs_len = self.xs.known_len().unwrap();
836                    self.limit = CheckedPow::checked_pow(u64::exact_from(xs_len), self.len);
837                    if Some(self.i) == self.limit {
838                        return None;
839                    }
840                    self.xs_done = true;
841                    // xs_len > 0 at this point
842                    self.distributor.set_max_bits(
843                        &[0],
844                        max(1, usize::wrapping_from((xs_len - 1).significant_bits())),
845                    );
846                } else {
847                    self.distributor.increment_counter();
848                }
849            }
850            let out = (0..usize::exact_from(self.len))
851                .map(|i| self.xs.get(self.distributor.get_output(i)).unwrap().clone())
852                .collect();
853            self.i += 1;
854            self.distributor.increment_counter();
855            Some(out)
856        }
857    }
858}
859
860fn exhaustive_vecs_fixed_length_1_input_g<I: Iterator>(
861    xs: I,
862    output_types: &[BitDistributorOutputType],
863) -> ExhaustiveFixedLengthVecs1InputG<I>
864where
865    I::Item: Clone,
866{
867    ExhaustiveFixedLengthVecs1InputG {
868        i: 0,
869        len: u64::exact_from(output_types.len()),
870        limit: None,
871        distributor: BitDistributor::new(output_types),
872        xs: IteratorCache::new(xs),
873        xs_done: false,
874        phantom: PhantomData,
875    }
876}
877
878/// Generates all [`Vec`]s of a given length with elements from a single iterator.
879///
880/// This `struct` is created by [`exhaustive_vecs_fixed_length_from_single`]; see its documentation
881/// for more.
882#[allow(clippy::large_enum_variant)]
883#[derive(Clone, Debug)]
884pub enum ExhaustiveFixedLengthVecs1Input<I: Iterator>
885where
886    I::Item: Clone,
887{
888    Zero(Once<Vec<I::Item>>),
889    One(I),
890    GreaterThanOne(ExhaustiveFixedLengthVecs1InputG<I>),
891}
892
893impl<I: Iterator> Iterator for ExhaustiveFixedLengthVecs1Input<I>
894where
895    I::Item: Clone,
896{
897    type Item = Vec<I::Item>;
898
899    fn next(&mut self) -> Option<Vec<I::Item>> {
900        match self {
901            ExhaustiveFixedLengthVecs1Input::Zero(xs) => xs.next(),
902            ExhaustiveFixedLengthVecs1Input::One(xs) => xs.next().map(|x| vec![x]),
903            ExhaustiveFixedLengthVecs1Input::GreaterThanOne(xs) => xs.next(),
904        }
905    }
906}
907
908/// Generates all length-$n$ [`Vec`]s with elements from a single iterator.
909///
910/// This function differs from [`exhaustive_vecs_fixed_length_from_single`] in that different
911/// [`BitDistributorOutputType`]s may be specified for each output element.
912///
913/// The $i$th element of `output_types` is a [`BitDistributorOutputType`] that determines how
914/// quickly the $i$th output slot advances through the iterator; see the [`BitDistributor`]
915/// documentation for a description of the different types. The length of the output [`Vec`]s, $n$,
916/// is specified by the length of `output_types`.
917///
918/// If `xs` is finite, the output length is $k^n$, where $k$ is `xs.count()` and $n$ is `len`. If
919/// `xs` is infinite, the output is also infinite.
920///
921/// If `len` is 0, the output consists of one empty [`Vec`].
922///
923/// If `xs` is empty, the output is also empty, unless `len` is 0.
924///
925/// # Examples
926/// ```
927/// use itertools::Itertools;
928/// use malachite_base::chars::exhaustive::exhaustive_ascii_chars;
929/// use malachite_base::iterators::bit_distributor::BitDistributorOutputType;
930/// use malachite_base::vecs::exhaustive::exhaustive_vecs_fixed_length_1_input;
931///
932/// // We are generating length-3 [`Vec`]s of chars using one input iterator, which produces all
933/// // ASCII chars. The third element has a tiny output type, so it will grow more slowly than the
934/// // other two elements (though it doesn't look that way from the first few [`Vec`]s).
935/// let xss = exhaustive_vecs_fixed_length_1_input(
936///     exhaustive_ascii_chars(),
937///     &[
938///         BitDistributorOutputType::normal(1),
939///         BitDistributorOutputType::normal(1),
940///         BitDistributorOutputType::tiny(),
941///     ],
942/// );
943/// let xss_prefix = xss.take(20).collect_vec();
944/// assert_eq!(
945///     xss_prefix
946///         .iter()
947///         .map(Vec::as_slice)
948///         .collect_vec()
949///         .as_slice(),
950///     &[
951///         &['a', 'a', 'a'],
952///         &['a', 'a', 'b'],
953///         &['a', 'a', 'c'],
954///         &['a', 'a', 'd'],
955///         &['a', 'b', 'a'],
956///         &['a', 'b', 'b'],
957///         &['a', 'b', 'c'],
958///         &['a', 'b', 'd'],
959///         &['a', 'a', 'e'],
960///         &['a', 'a', 'f'],
961///         &['a', 'a', 'g'],
962///         &['a', 'a', 'h'],
963///         &['a', 'b', 'e'],
964///         &['a', 'b', 'f'],
965///         &['a', 'b', 'g'],
966///         &['a', 'b', 'h'],
967///         &['b', 'a', 'a'],
968///         &['b', 'a', 'b'],
969///         &['b', 'a', 'c'],
970///         &['b', 'a', 'd']
971///     ]
972/// );
973/// ```
974pub fn exhaustive_vecs_fixed_length_1_input<I: Iterator>(
975    xs: I,
976    output_types: &[BitDistributorOutputType],
977) -> ExhaustiveFixedLengthVecs1Input<I>
978where
979    I::Item: Clone,
980{
981    match output_types.len() {
982        0 => ExhaustiveFixedLengthVecs1Input::Zero(once(Vec::new())),
983        1 => ExhaustiveFixedLengthVecs1Input::One(xs),
984        _ => ExhaustiveFixedLengthVecs1Input::GreaterThanOne(
985            exhaustive_vecs_fixed_length_1_input_g(xs, output_types),
986        ),
987    }
988}
989
990/// Generates all [`Vec`]s of a given length with elements from a single iterator.
991///
992/// If `xs` is finite, the output length is $\ell^n$, where $\ell$ is `xs.count()` and $n$ is `len`.
993/// If `xs` is infinite, the output is also infinite.
994///
995/// If `len` is 0, the output consists of one empty [`Vec`].
996///
997/// If `xs` is empty, the output is also empty, unless `len` is 0.
998///
999/// # Examples
1000/// ```
1001/// use itertools::Itertools;
1002/// use malachite_base::vecs::exhaustive::exhaustive_vecs_fixed_length_from_single;
1003///
1004/// let xss = exhaustive_vecs_fixed_length_from_single(2, 0..4).collect_vec();
1005/// assert_eq!(
1006///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
1007///     &[
1008///         &[0, 0],
1009///         &[0, 1],
1010///         &[1, 0],
1011///         &[1, 1],
1012///         &[0, 2],
1013///         &[0, 3],
1014///         &[1, 2],
1015///         &[1, 3],
1016///         &[2, 0],
1017///         &[2, 1],
1018///         &[3, 0],
1019///         &[3, 1],
1020///         &[2, 2],
1021///         &[2, 3],
1022///         &[3, 2],
1023///         &[3, 3]
1024///     ]
1025/// );
1026/// ```
1027#[inline]
1028pub fn exhaustive_vecs_fixed_length_from_single<I: Iterator>(
1029    len: u64,
1030    xs: I,
1031) -> ExhaustiveFixedLengthVecs1Input<I>
1032where
1033    I::Item: Clone,
1034{
1035    exhaustive_vecs_fixed_length_1_input(
1036        xs,
1037        &vec![BitDistributorOutputType::normal(1); usize::exact_from(len)],
1038    )
1039}
1040
1041#[derive(Clone, Debug)]
1042struct LexVecsGenerator<Y: Clone, J: Clone + Iterator<Item = Y>> {
1043    ys: J,
1044}
1045
1046impl<Y: Clone, J: Clone + Iterator<Item = Y>>
1047    ExhaustiveDependentPairsYsGenerator<u64, Vec<Y>, LexFixedLengthVecsFromSingle<J>>
1048    for LexVecsGenerator<Y, J>
1049{
1050    #[inline]
1051    fn get_ys(&self, &x: &u64) -> LexFixedLengthVecsFromSingle<J> {
1052        lex_vecs_fixed_length_from_single(x, self.ys.clone())
1053    }
1054}
1055
1056#[inline]
1057const fn shortlex_vecs_from_element_iterator_helper<
1058    T: Clone,
1059    I: Iterator<Item = u64>,
1060    J: Clone + Iterator<Item = T>,
1061>(
1062    xs: I,
1063    ys: J,
1064) -> LexDependentPairs<u64, Vec<T>, LexVecsGenerator<T, J>, I, LexFixedLengthVecsFromSingle<J>> {
1065    lex_dependent_pairs_stop_after_empty_ys(xs, LexVecsGenerator { ys })
1066}
1067
1068/// Generates all [`Vec`]s with elements from a specified iterator and with lengths from another
1069/// iterator.
1070#[derive(Clone, Debug)]
1071pub struct ShortlexVecs<T: Clone, I: Iterator<Item = u64>, J: Clone + Iterator<Item = T>>(
1072    LexDependentPairs<u64, Vec<T>, LexVecsGenerator<T, J>, I, LexFixedLengthVecsFromSingle<J>>,
1073);
1074
1075impl<T: Clone, I: Iterator<Item = u64>, J: Clone + Iterator<Item = T>> Iterator
1076    for ShortlexVecs<T, I, J>
1077{
1078    type Item = Vec<T>;
1079
1080    #[inline]
1081    fn next(&mut self) -> Option<Vec<T>> {
1082        self.0.next().map(|p| p.1)
1083    }
1084}
1085
1086/// Generates all [`Vec`]s with elements from a specified iterator and with lengths from another
1087/// iterator.
1088///
1089/// The length-generating iterator is `xs`, and the element-generating iterator is `ys`.
1090///
1091/// If the provided lengths are $\ell_0, \ell_1, \ell_2, \ldots$, then first all [`Vec`]s with
1092/// length $\ell_0$ will be generated, in lexicographic order; then all [`Vec`]s with length
1093/// $\ell_2$, and so on. If the lengths iterator has repetitions, then the generated [`Vec`]s will
1094/// be repeated too.
1095///
1096/// `ys` must be finite; if it's infinite, the output will never get past the first nonzero $\ell$.
1097///
1098/// There's one quirk if `ys` is empty: then the iterator will stop as soon as it encounters a
1099/// nonzero $\ell$, even if there are zeros later on. This prevents the iterator hanging when given
1100/// an empty `ys` and lengths $0, 1, 2, \ldots$.
1101///
1102/// If `ys` is empty, the output length is the amount of zeros generated by `xs` before the first
1103/// nonzero length. If `ys` is nonempty and `xs` is infinite, the output is infinite. Finally, if
1104/// `ys` is nonempty and `xs` is finite, the output length is
1105/// $$
1106/// \sum_{k=0}^{m-1} n^{\ell_k},
1107/// $$
1108/// where $n$ is `ys.count()` and $m$ is `xs.count()`.
1109///
1110/// # Examples
1111/// ```
1112/// use itertools::Itertools;
1113/// use malachite_base::bools::exhaustive::exhaustive_bools;
1114/// use malachite_base::nevers::nevers;
1115/// use malachite_base::vecs::exhaustive::shortlex_vecs_from_length_iterator;
1116///
1117/// let xss = shortlex_vecs_from_length_iterator([2, 1, 2].iter().cloned(), exhaustive_bools())
1118///     .collect_vec();
1119/// assert_eq!(
1120///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
1121///     &[
1122///         &[false, false][..],
1123///         &[false, true],
1124///         &[true, false],
1125///         &[true, true],
1126///         &[false],
1127///         &[true],
1128///         &[false, false],
1129///         &[false, true],
1130///         &[true, false],
1131///         &[true, true]
1132///     ]
1133/// );
1134///
1135/// let xss =
1136///     shortlex_vecs_from_length_iterator([0, 0, 1, 0].iter().cloned(), nevers()).collect_vec();
1137/// // Stops after first empty ys
1138/// assert_eq!(
1139///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
1140///     &[&[], &[]]
1141/// );
1142/// ```
1143#[inline]
1144pub const fn shortlex_vecs_from_length_iterator<
1145    T: Clone,
1146    I: Iterator<Item = u64>,
1147    J: Clone + Iterator<Item = T>,
1148>(
1149    xs: I,
1150    ys: J,
1151) -> ShortlexVecs<T, I, J> {
1152    ShortlexVecs(shortlex_vecs_from_element_iterator_helper(xs, ys))
1153}
1154
1155/// Generates [`Vec`]s with elements from a specified iterator, in shortlex order.
1156///
1157/// Shortlex order means that the [`Vec`]s are output from shortest to longest, and [`Vec`]s of the
1158/// same length are output in lexicographic order with respect to the ordering of the [`Vec`]
1159/// elements specified by the input iterator.
1160///
1161/// `xs` must be finite; if it's infinite, only [`Vec`]s of length 0 and 1 are ever produced.
1162///
1163/// If `xs` is empty, the output length is 1; otherwise, the output is infinite.
1164///
1165/// The lengths of the output [`Vec`]s grow logarithmically.
1166///
1167/// # Examples
1168/// ```
1169/// use itertools::Itertools;
1170/// use malachite_base::bools::exhaustive::exhaustive_bools;
1171/// use malachite_base::vecs::exhaustive::shortlex_vecs;
1172///
1173/// let bss = shortlex_vecs(exhaustive_bools()).take(20).collect_vec();
1174/// assert_eq!(
1175///     bss.iter().map(Vec::as_slice).collect_vec().as_slice(),
1176///     &[
1177///         &[][..],
1178///         &[false],
1179///         &[true],
1180///         &[false, false],
1181///         &[false, true],
1182///         &[true, false],
1183///         &[true, true],
1184///         &[false, false, false],
1185///         &[false, false, true],
1186///         &[false, true, false],
1187///         &[false, true, true],
1188///         &[true, false, false],
1189///         &[true, false, true],
1190///         &[true, true, false],
1191///         &[true, true, true],
1192///         &[false, false, false, false],
1193///         &[false, false, false, true],
1194///         &[false, false, true, false],
1195///         &[false, false, true, true],
1196///         &[false, true, false, false]
1197///     ]
1198/// );
1199/// ```
1200#[inline]
1201pub fn shortlex_vecs<I: Clone + Iterator>(
1202    xs: I,
1203) -> ShortlexVecs<I::Item, PrimitiveIntIncreasingRange<u64>, I>
1204where
1205    I::Item: Clone,
1206{
1207    shortlex_vecs_from_length_iterator(exhaustive_unsigneds(), xs)
1208}
1209
1210/// Generates all [`Vec`]s with a minimum length and with elements from a specified iterator, in
1211/// shortlex order.
1212///
1213/// Shortlex order means that the [`Vec`]s are output from shortest to longest, and [`Vec`]s of the
1214/// same length are output in lexicographic order with respect to the ordering of the [`Vec`]
1215/// elements specified by the input iterator.
1216///
1217/// `xs` must be finite; if it's infinite, only [`Vec`]s of length `min_length` (or 0 and 1, if
1218/// `min_length` is 0) are ever produced.
1219///
1220/// If `xs` is empty and `min_length` is 0, the output length is 1; if `xs` is empty and
1221/// `min_length` is greater than 0, the output is empty; otherwise, the output is infinite.
1222///
1223/// The lengths of the output [`Vec`]s grow logarithmically.
1224///
1225/// # Examples
1226/// ```
1227/// use itertools::Itertools;
1228/// use malachite_base::bools::exhaustive::exhaustive_bools;
1229/// use malachite_base::vecs::exhaustive::shortlex_vecs_min_length;
1230///
1231/// let bss = shortlex_vecs_min_length(2, exhaustive_bools())
1232///     .take(20)
1233///     .collect_vec();
1234/// assert_eq!(
1235///     bss.iter().map(Vec::as_slice).collect_vec().as_slice(),
1236///     &[
1237///         &[false, false][..],
1238///         &[false, true],
1239///         &[true, false],
1240///         &[true, true],
1241///         &[false, false, false],
1242///         &[false, false, true],
1243///         &[false, true, false],
1244///         &[false, true, true],
1245///         &[true, false, false],
1246///         &[true, false, true],
1247///         &[true, true, false],
1248///         &[true, true, true],
1249///         &[false, false, false, false],
1250///         &[false, false, false, true],
1251///         &[false, false, true, false],
1252///         &[false, false, true, true],
1253///         &[false, true, false, false],
1254///         &[false, true, false, true],
1255///         &[false, true, true, false],
1256///         &[false, true, true, true]
1257///     ]
1258/// );
1259/// ```
1260#[inline]
1261pub fn shortlex_vecs_min_length<I: Clone + Iterator>(
1262    min_length: u64,
1263    xs: I,
1264) -> ShortlexVecs<I::Item, PrimitiveIntIncreasingRange<u64>, I>
1265where
1266    I::Item: Clone,
1267{
1268    shortlex_vecs_from_length_iterator(
1269        primitive_int_increasing_inclusive_range(min_length, u64::MAX),
1270        xs,
1271    )
1272}
1273
1274/// Generates all [`Vec`]s with lengths in $[a, b)$ and with elements from a specified iterator, in
1275/// shortlex order.
1276///
1277/// Shortlex order means that the [`Vec`]s are output from shortest to longest, and [`Vec`]s of the
1278/// same length are output in lexicographic order with respect to the ordering of the [`Vec`]
1279/// elements specified by the input iterator.
1280///
1281/// `xs` must be finite; if it's infinite and $a < b$, only [`Vec`]s of length `a` (or 0 and 1, if
1282/// `a` is 0) are ever produced.
1283///
1284/// The output length is
1285/// $$
1286/// \sum_{k=a}^{b-1} n^k,
1287/// $$
1288/// where $k$ is `xs.count()`.
1289///
1290/// The lengths of the output [`Vec`]s grow logarithmically.
1291///
1292/// # Examples
1293/// ```
1294/// use itertools::Itertools;
1295/// use malachite_base::bools::exhaustive::exhaustive_bools;
1296/// use malachite_base::vecs::exhaustive::shortlex_vecs_length_range;
1297///
1298/// let bss = shortlex_vecs_length_range(2, 4, exhaustive_bools()).collect_vec();
1299/// assert_eq!(
1300///     bss.iter().map(Vec::as_slice).collect_vec().as_slice(),
1301///     &[
1302///         &[false, false][..],
1303///         &[false, true],
1304///         &[true, false],
1305///         &[true, true],
1306///         &[false, false, false],
1307///         &[false, false, true],
1308///         &[false, true, false],
1309///         &[false, true, true],
1310///         &[true, false, false],
1311///         &[true, false, true],
1312///         &[true, true, false],
1313///         &[true, true, true]
1314///     ]
1315/// );
1316/// ```
1317#[inline]
1318pub fn shortlex_vecs_length_range<I: Clone + Iterator>(
1319    a: u64,
1320    mut b: u64,
1321    xs: I,
1322) -> ShortlexVecs<I::Item, PrimitiveIntIncreasingRange<u64>, I>
1323where
1324    I::Item: Clone,
1325{
1326    if a > b {
1327        b = a;
1328    }
1329    shortlex_vecs_from_length_iterator(primitive_int_increasing_range(a, b), xs)
1330}
1331
1332/// Generates all [`Vec`]s with lengths in $[a, b]$ and with elements from a specified iterator, in
1333/// shortlex order.
1334///
1335/// Shortlex order means that the [`Vec`]s are output from shortest to longest, and [`Vec`]s of the
1336/// same length are output in lexicographic order with respect to the ordering of the [`Vec`]
1337/// elements specified by the input iterator.
1338///
1339/// `xs` must be finite; if it's infinite, only [`Vec`]s of length `a` (or 0 and 1, if `a` is 0) are
1340/// ever produced.
1341///
1342/// The output length is
1343/// $$
1344/// \sum_{k=a}^b n^k,
1345/// $$
1346/// where $k$ is `xs.count()`.
1347///
1348/// The lengths of the output [`Vec`]s grow logarithmically.
1349///
1350/// # Examples
1351/// ```
1352/// use itertools::Itertools;
1353/// use malachite_base::bools::exhaustive::exhaustive_bools;
1354/// use malachite_base::vecs::exhaustive::shortlex_vecs_length_inclusive_range;
1355///
1356/// let bss = shortlex_vecs_length_inclusive_range(2, 3, exhaustive_bools()).collect_vec();
1357/// assert_eq!(
1358///     bss.iter().map(Vec::as_slice).collect_vec().as_slice(),
1359///     &[
1360///         &[false, false][..],
1361///         &[false, true],
1362///         &[true, false],
1363///         &[true, true],
1364///         &[false, false, false],
1365///         &[false, false, true],
1366///         &[false, true, false],
1367///         &[false, true, true],
1368///         &[true, false, false],
1369///         &[true, false, true],
1370///         &[true, true, false],
1371///         &[true, true, true]
1372///     ]
1373/// );
1374/// ```
1375#[inline]
1376pub fn shortlex_vecs_length_inclusive_range<I: Clone + Iterator>(
1377    mut a: u64,
1378    mut b: u64,
1379    xs: I,
1380) -> ShortlexVecs<I::Item, PrimitiveIntIncreasingRange<u64>, I>
1381where
1382    I::Item: Clone,
1383{
1384    if a > b {
1385        a = 1;
1386        b = 0;
1387    }
1388    shortlex_vecs_from_length_iterator(primitive_int_increasing_range(a, b.saturating_add(1)), xs)
1389}
1390
1391#[doc(hidden)]
1392#[derive(Clone, Debug)]
1393struct ExhaustiveVecsGenerator<Y: Clone, J: Clone + Iterator<Item = Y>> {
1394    ys: J,
1395}
1396
1397impl<Y: Clone, J: Clone + Iterator<Item = Y>>
1398    ExhaustiveDependentPairsYsGenerator<u64, Vec<Y>, ExhaustiveFixedLengthVecs1Input<J>>
1399    for ExhaustiveVecsGenerator<Y, J>
1400{
1401    #[inline]
1402    fn get_ys(&self, &x: &u64) -> ExhaustiveFixedLengthVecs1Input<J> {
1403        exhaustive_vecs_fixed_length_1_input(
1404            self.ys.clone(),
1405            &vec![BitDistributorOutputType::normal(1); usize::exact_from(x)],
1406        )
1407    }
1408}
1409
1410#[inline]
1411const fn exhaustive_vecs_from_element_iterator_helper<
1412    T: Clone,
1413    I: Iterator<Item = u64>,
1414    J: Clone + Iterator<Item = T>,
1415>(
1416    xs: I,
1417    ys: J,
1418) -> ExhaustiveDependentPairs<
1419    u64,
1420    Vec<T>,
1421    RulerSequence<usize>,
1422    ExhaustiveVecsGenerator<T, J>,
1423    I,
1424    ExhaustiveFixedLengthVecs1Input<J>,
1425> {
1426    exhaustive_dependent_pairs_stop_after_empty_ys(
1427        ruler_sequence(),
1428        xs,
1429        ExhaustiveVecsGenerator { ys },
1430    )
1431}
1432
1433/// Generates all [`Vec`]s with elements from a specified iterator and with lengths from another
1434/// iterator.
1435#[derive(Clone, Debug)]
1436pub struct ExhaustiveVecs<T: Clone, I: Iterator<Item = u64>, J: Clone + Iterator<Item = T>>(
1437    ExhaustiveDependentPairs<
1438        u64,
1439        Vec<T>,
1440        RulerSequence<usize>,
1441        ExhaustiveVecsGenerator<T, J>,
1442        I,
1443        ExhaustiveFixedLengthVecs1Input<J>,
1444    >,
1445);
1446
1447impl<T: Clone, I: Iterator<Item = u64>, J: Clone + Iterator<Item = T>> Iterator
1448    for ExhaustiveVecs<T, I, J>
1449{
1450    type Item = Vec<T>;
1451
1452    #[inline]
1453    fn next(&mut self) -> Option<Vec<T>> {
1454        self.0.next().map(|p| p.1)
1455    }
1456}
1457
1458/// Generates all [`Vec`]s with elements from a specified iterator and with lengths from another
1459/// iterator.
1460///
1461/// The length-generating iterator is `xs`, and the element-generating iterator is `ys`.
1462///
1463/// If the lengths iterator has repetitions, then the generated [`Vec`]s will be repeated too.
1464///
1465/// There's one quirk if `ys` is empty: then the iterator will stop at some point after it
1466/// encounters a nonzero $\ell$, even if there are zeros later on. This prevents the iterator
1467/// hanging when given an empty `ys` and lengths $0, 1, 2, \ldots$.
1468///
1469/// - If `ys` is empty, the output length is finite.
1470/// - If `ys` is infinite, the output length is infinite.
1471/// - If `ys` is nonempty and finite, and `xs` is infinite, the output is infinite.
1472/// - If `ys` is nonempty and finite, and `xs` is finite, the output length is
1473///   $$
1474///   \sum_{k=0}^{m-1} n^{\ell_k},
1475///   $$
1476///   where $n$ is `ys.count()` and $m$ is `xs.count()`.
1477///
1478/// # Examples
1479/// ```
1480/// use itertools::Itertools;
1481/// use malachite_base::bools::exhaustive::exhaustive_bools;
1482/// use malachite_base::nevers::nevers;
1483/// use malachite_base::vecs::exhaustive::exhaustive_vecs_from_length_iterator;
1484///
1485/// let xss = exhaustive_vecs_from_length_iterator([2, 1, 2].iter().cloned(), exhaustive_bools())
1486///     .collect_vec();
1487/// assert_eq!(
1488///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
1489///     &[
1490///         &[false, false][..],
1491///         &[false],
1492///         &[false, true],
1493///         &[false, false],
1494///         &[true, false],
1495///         &[true],
1496///         &[true, true],
1497///         &[false, true],
1498///         &[true, false],
1499///         &[true, true]
1500///     ]
1501/// );
1502///
1503/// let xss =
1504///     exhaustive_vecs_from_length_iterator([0, 0, 1, 0].iter().cloned(), nevers()).collect_vec();
1505/// // Stops at some point after first empty ys
1506/// assert_eq!(
1507///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
1508///     &[&[], &[]]
1509/// );
1510/// ```
1511#[inline]
1512pub const fn exhaustive_vecs_from_length_iterator<
1513    T: Clone,
1514    I: Iterator<Item = u64>,
1515    J: Clone + Iterator<Item = T>,
1516>(
1517    lengths: I,
1518    xs: J,
1519) -> ExhaustiveVecs<T, I, J> {
1520    ExhaustiveVecs(exhaustive_vecs_from_element_iterator_helper(lengths, xs))
1521}
1522
1523/// Generates all [`Vec`]s with elements from a specified iterator.
1524///
1525/// If `xs` is empty, the output length is 1; otherwise, the output is infinite.
1526///
1527/// The lengths of the output [`Vec`]s grow logarithmically.
1528///
1529/// # Examples
1530/// ```
1531/// use itertools::Itertools;
1532/// use malachite_base::num::exhaustive::exhaustive_unsigneds;
1533/// use malachite_base::vecs::exhaustive::exhaustive_vecs;
1534///
1535/// let xss = exhaustive_vecs(exhaustive_unsigneds::<u32>())
1536///     .take(20)
1537///     .collect_vec();
1538/// assert_eq!(
1539///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
1540///     &[
1541///         &[][..],
1542///         &[0],
1543///         &[1],
1544///         &[0, 0, 0],
1545///         &[2],
1546///         &[0, 0],
1547///         &[3],
1548///         &[0, 0, 0, 0],
1549///         &[4],
1550///         &[0, 1],
1551///         &[5],
1552///         &[0, 0, 1],
1553///         &[6],
1554///         &[1, 0],
1555///         &[7],
1556///         &[0, 0, 0, 0, 0],
1557///         &[8],
1558///         &[1, 1],
1559///         &[9],
1560///         &[0, 1, 0]
1561///     ]
1562/// );
1563/// ```
1564#[inline]
1565pub fn exhaustive_vecs<I: Clone + Iterator>(
1566    xs: I,
1567) -> ExhaustiveVecs<I::Item, PrimitiveIntIncreasingRange<u64>, I>
1568where
1569    I::Item: Clone,
1570{
1571    exhaustive_vecs_from_length_iterator(exhaustive_unsigneds(), xs)
1572}
1573
1574/// Generates all [`Vec`]s with a minimum length and with elements from a specified iterator.
1575///
1576/// If `xs` is empty and `min_length` is 0, the output length is 1; if `xs` is empty and
1577/// `min_length` is greater than 0, the output is empty; otherwise, the output is infinite.
1578///
1579/// The lengths of the output [`Vec`]s grow logarithmically.
1580///
1581/// # Examples
1582/// ```
1583/// use itertools::Itertools;
1584/// use malachite_base::num::exhaustive::exhaustive_unsigneds;
1585/// use malachite_base::vecs::exhaustive::exhaustive_vecs_min_length;
1586///
1587/// let xss = exhaustive_vecs_min_length(2, exhaustive_unsigneds::<u32>())
1588///     .take(20)
1589///     .collect_vec();
1590/// assert_eq!(
1591///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
1592///     &[
1593///         &[0, 0][..],
1594///         &[0, 0, 0],
1595///         &[0, 1],
1596///         &[0, 0, 0, 0],
1597///         &[1, 0],
1598///         &[0, 0, 1],
1599///         &[1, 1],
1600///         &[0, 0, 0, 0, 0],
1601///         &[0, 2],
1602///         &[0, 1, 0],
1603///         &[0, 3],
1604///         &[0, 0, 0, 1],
1605///         &[1, 2],
1606///         &[0, 1, 1],
1607///         &[1, 3],
1608///         &[0, 0, 0, 0, 0, 0],
1609///         &[2, 0],
1610///         &[1, 0, 0],
1611///         &[2, 1],
1612///         &[0, 0, 1, 0]
1613///     ]
1614/// );
1615/// ```
1616#[inline]
1617pub fn exhaustive_vecs_min_length<I: Clone + Iterator>(
1618    min_length: u64,
1619    xs: I,
1620) -> ExhaustiveVecs<I::Item, PrimitiveIntIncreasingRange<u64>, I>
1621where
1622    I::Item: Clone,
1623{
1624    exhaustive_vecs_from_length_iterator(
1625        primitive_int_increasing_inclusive_range(min_length, u64::MAX),
1626        xs,
1627    )
1628}
1629
1630/// Generates all [`Vec`]s with lengths in $[a, b)$ and with elements from a specified iterator.
1631///
1632/// - If $a \geq b$, the output length is 0.
1633/// - If $a = 0$ and $b = 1$, the output length is 1.
1634/// - If $a < b$, $b > 1$, and `xs` is infinite, the output length is infinite.
1635/// - If `xs` is finite, the output length is
1636///   $$
1637///   \sum_{k=a}^{b-1} n^k,
1638///   $$
1639///   where $k$ is `xs.count()`.
1640///
1641/// The lengths of the output [`Vec`]s grow logarithmically.
1642///
1643/// # Examples
1644/// ```
1645/// use itertools::Itertools;
1646/// use malachite_base::num::exhaustive::exhaustive_unsigneds;
1647/// use malachite_base::vecs::exhaustive::exhaustive_vecs_length_range;
1648///
1649/// let xss = exhaustive_vecs_length_range(2, 4, exhaustive_unsigneds::<u32>())
1650///     .take(20)
1651///     .collect_vec();
1652/// assert_eq!(
1653///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
1654///     &[
1655///         &[0, 0][..],
1656///         &[0, 0, 0],
1657///         &[0, 1],
1658///         &[1, 0],
1659///         &[1, 1],
1660///         &[0, 0, 1],
1661///         &[0, 2],
1662///         &[0, 1, 0],
1663///         &[0, 3],
1664///         &[0, 1, 1],
1665///         &[1, 2],
1666///         &[1, 3],
1667///         &[2, 0],
1668///         &[1, 0, 0],
1669///         &[2, 1],
1670///         &[3, 0],
1671///         &[3, 1],
1672///         &[1, 0, 1],
1673///         &[2, 2],
1674///         &[2, 3]
1675///     ]
1676/// );
1677/// ```
1678#[inline]
1679pub fn exhaustive_vecs_length_range<I: Clone + Iterator>(
1680    a: u64,
1681    mut b: u64,
1682    xs: I,
1683) -> ExhaustiveVecs<I::Item, PrimitiveIntIncreasingRange<u64>, I>
1684where
1685    I::Item: Clone,
1686{
1687    if a > b {
1688        b = a;
1689    }
1690    exhaustive_vecs_from_length_iterator(primitive_int_increasing_range(a, b), xs)
1691}
1692
1693/// Generates all [`Vec`]s with lengths in $[a, b]$ and with elements from a specified iterator.
1694///
1695/// - If $a > b$, the output length is 0.
1696/// - If $a = b = 0$, the output length is 1.
1697/// - If $a < b$, $b > 0$, and `xs` is infinite, the output length is infinite.
1698/// - If `xs` is finite, the output length is
1699///   $$
1700///   \sum_{k=a}^b n^k,
1701///   $$
1702///   where $k$ is `xs.count()`.
1703///
1704/// The lengths of the output [`Vec`]s grow logarithmically.
1705///
1706/// # Panics
1707/// Panics if $a > b$.
1708///
1709/// # Examples
1710/// ```
1711/// use itertools::Itertools;
1712/// use malachite_base::num::exhaustive::exhaustive_unsigneds;
1713/// use malachite_base::vecs::exhaustive::exhaustive_vecs_length_inclusive_range;
1714///
1715/// let xss = exhaustive_vecs_length_inclusive_range(2, 4, exhaustive_unsigneds::<u32>())
1716///     .take(20)
1717///     .collect_vec();
1718/// assert_eq!(
1719///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
1720///     &[
1721///         &[0, 0][..],
1722///         &[0, 0, 0],
1723///         &[0, 1],
1724///         &[0, 0, 0, 0],
1725///         &[1, 0],
1726///         &[0, 0, 1],
1727///         &[1, 1],
1728///         &[0, 2],
1729///         &[0, 3],
1730///         &[0, 1, 0],
1731///         &[1, 2],
1732///         &[0, 0, 0, 1],
1733///         &[1, 3],
1734///         &[0, 1, 1],
1735///         &[2, 0],
1736///         &[1, 0, 0],
1737///         &[2, 1],
1738///         &[1, 0, 1],
1739///         &[3, 0],
1740///         &[0, 0, 1, 0]
1741///     ]
1742/// );
1743/// ```
1744#[inline]
1745pub fn exhaustive_vecs_length_inclusive_range<I: Clone + Iterator>(
1746    mut a: u64,
1747    mut b: u64,
1748    xs: I,
1749) -> ExhaustiveVecs<I::Item, PrimitiveIntIncreasingRange<u64>, I>
1750where
1751    I::Item: Clone,
1752{
1753    if a > b {
1754        a = 1;
1755        b = 0;
1756    }
1757    exhaustive_vecs_from_length_iterator(primitive_int_increasing_range(a, b.saturating_add(1)), xs)
1758}
1759
1760/// Generates all collections of elements from an iterator, where the collections are of a fixed
1761/// length, have no repetitions, and are ordered the same way as in the iterator.
1762#[derive(Clone, Debug)]
1763pub struct LexFixedLengthOrderedUniqueCollections<I: Iterator, C: FromIterator<I::Item>>
1764where
1765    I::Item: Clone,
1766{
1767    first: bool,
1768    done: bool,
1769    xs: IteratorCache<I>,
1770    indices: Vec<usize>,
1771    phantom_i: PhantomData<*const I::Item>,
1772    phantom_c: PhantomData<*const C>,
1773}
1774
1775impl<I: Iterator, C: FromIterator<I::Item>> LexFixedLengthOrderedUniqueCollections<I, C>
1776where
1777    I::Item: Clone,
1778{
1779    pub fn new(k: u64, xs: I) -> LexFixedLengthOrderedUniqueCollections<I, C> {
1780        LexFixedLengthOrderedUniqueCollections {
1781            first: true,
1782            done: false,
1783            xs: IteratorCache::new(xs),
1784            indices: (0..usize::exact_from(k)).collect(),
1785            phantom_i: PhantomData,
1786            phantom_c: PhantomData,
1787        }
1788    }
1789}
1790
1791#[doc(hidden)]
1792pub fn fixed_length_ordered_unique_indices_helper(
1793    n: usize,
1794    k: usize,
1795    indices: &mut [usize],
1796) -> bool {
1797    let mut expected_j = n - 1;
1798    let mut i = k - 1;
1799    // Find longest suffix of the form [..., n - 3, n - 2, n - 1]. After this loop, i is the index
1800    // right before this longest suffix.
1801    loop {
1802        if expected_j != indices[i] {
1803            break;
1804        }
1805        if i == 0 {
1806            return true;
1807        }
1808        i -= 1;
1809        expected_j -= 1;
1810    }
1811    let mut j = indices[i] + 1;
1812    for index in &mut indices[i..] {
1813        *index = j;
1814        j += 1;
1815    }
1816    false
1817}
1818
1819impl<I: Iterator, C: FromIterator<I::Item>> Iterator
1820    for LexFixedLengthOrderedUniqueCollections<I, C>
1821where
1822    I::Item: Clone,
1823{
1824    type Item = C;
1825
1826    fn next(&mut self) -> Option<C> {
1827        if self.done {
1828            return None;
1829        }
1830        let k = self.indices.len();
1831        if self.first {
1832            self.first = false;
1833            self.xs.get(k);
1834            if let Some(n) = self.xs.known_len() {
1835                if n < k {
1836                    self.done = true;
1837                    return None;
1838                }
1839            }
1840        } else {
1841            if k == 0 {
1842                self.done = true;
1843                return None;
1844            }
1845            if let Some(n) = self.xs.known_len() {
1846                if fixed_length_ordered_unique_indices_helper(n, k, &mut self.indices) {
1847                    self.done = true;
1848                    return None;
1849                }
1850            } else {
1851                *self.indices.last_mut().unwrap() += 1;
1852            }
1853        }
1854        if let Some(&last_index) = self.indices.last() {
1855            // Give known len a chance to be set
1856            self.xs.get(last_index + 1);
1857        }
1858        Some(
1859            self.indices
1860                .iter()
1861                .map(|&i| self.xs.assert_get(i).clone())
1862                .collect(),
1863        )
1864    }
1865}
1866
1867/// Generates [`Vec`]s of a given length with elements from a single iterator, such that each
1868/// [`Vec`] has no repeated elements, and the elements in each [`Vec`] are ordered the same way as
1869/// they are in the source iterator.
1870///
1871/// The source iterator should not repeat any elements, but this is not enforced.
1872///
1873/// The order is lexicographic with respect to the order of the element iterator.
1874///
1875/// If $k$ is 0, the output length is 1.
1876///
1877/// If $k$ is nonzero and the input iterator is infinite, the output length is also infinite.
1878///
1879/// If $k$ is nonzero and the input iterator length is $n$, the output length is $\binom{n}{k}$.
1880///
1881/// If $k$ is 0, the output consists of one empty [`Vec`].
1882///
1883/// If `xs` is empty, the output is also empty, unless $k$ is 0.
1884///
1885/// # Examples
1886/// ```
1887/// use itertools::Itertools;
1888/// use malachite_base::vecs::exhaustive::lex_ordered_unique_vecs_fixed_length;
1889///
1890/// let xss = lex_ordered_unique_vecs_fixed_length(4, 1..=6).collect_vec();
1891/// assert_eq!(
1892///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
1893///     &[
1894///         &[1, 2, 3, 4],
1895///         &[1, 2, 3, 5],
1896///         &[1, 2, 3, 6],
1897///         &[1, 2, 4, 5],
1898///         &[1, 2, 4, 6],
1899///         &[1, 2, 5, 6],
1900///         &[1, 3, 4, 5],
1901///         &[1, 3, 4, 6],
1902///         &[1, 3, 5, 6],
1903///         &[1, 4, 5, 6],
1904///         &[2, 3, 4, 5],
1905///         &[2, 3, 4, 6],
1906///         &[2, 3, 5, 6],
1907///         &[2, 4, 5, 6],
1908///         &[3, 4, 5, 6]
1909///     ]
1910/// );
1911/// ```
1912#[inline]
1913pub fn lex_ordered_unique_vecs_fixed_length<I: Iterator>(
1914    k: u64,
1915    xs: I,
1916) -> LexFixedLengthOrderedUniqueCollections<I, Vec<I::Item>>
1917where
1918    I::Item: Clone,
1919{
1920    LexFixedLengthOrderedUniqueCollections::new(k, xs)
1921}
1922
1923/// Generates all collections of elements from an iterator in shortlex order, where the collections
1924/// have no repetitions and are ordered the same way as in the iterator.
1925#[derive(Clone)]
1926pub struct ShortlexOrderedUniqueCollections<I: Clone + Iterator, C: FromIterator<I::Item>>
1927where
1928    I::Item: Clone,
1929{
1930    current_len: u64,
1931    max_len: u64,
1932    xs: I,
1933    current_xss: LexFixedLengthOrderedUniqueCollections<I, C>,
1934}
1935
1936impl<I: Clone + Iterator, C: FromIterator<I::Item>> ShortlexOrderedUniqueCollections<I, C>
1937where
1938    I::Item: Clone,
1939{
1940    pub(crate) fn new(a: u64, b: u64, xs: I) -> ShortlexOrderedUniqueCollections<I, C> {
1941        ShortlexOrderedUniqueCollections {
1942            current_len: a,
1943            max_len: b,
1944            xs: xs.clone(),
1945            current_xss: LexFixedLengthOrderedUniqueCollections::new(a, xs),
1946        }
1947    }
1948}
1949
1950impl<I: Clone + Iterator, C: FromIterator<I::Item>> Iterator
1951    for ShortlexOrderedUniqueCollections<I, C>
1952where
1953    I::Item: Clone,
1954{
1955    type Item = C;
1956
1957    fn next(&mut self) -> Option<C> {
1958        if self.current_len > self.max_len {
1959            return None;
1960        }
1961        if let Some(next) = self.current_xss.next() {
1962            Some(next)
1963        } else {
1964            self.current_len += 1;
1965            if self.current_len > self.max_len {
1966                return None;
1967            }
1968            self.current_xss = LexFixedLengthOrderedUniqueCollections {
1969                first: true,
1970                done: false,
1971                xs: IteratorCache::new(self.xs.clone()),
1972                indices: (0..usize::exact_from(self.current_len)).collect(),
1973                phantom_i: PhantomData,
1974                phantom_c: PhantomData,
1975            };
1976            if let Some(next) = self.current_xss.next() {
1977                Some(next)
1978            } else {
1979                // Prevent any further iteration
1980                self.max_len = 0;
1981                self.current_len = 1;
1982                None
1983            }
1984        }
1985    }
1986}
1987
1988/// Generates [`Vec`]s with elements from a single iterator, such that each [`Vec`] has no repeated
1989/// elements, and the elements in each [`Vec`] are ordered the same way as they are in the source
1990/// iterator.
1991///
1992/// The [`Vec`]s are generated in order of increasing length, and within each length they are
1993/// ordered lexicographically with respect to the order of the element iterator.
1994///
1995/// The source iterator should not repeat any elements, but this is not enforced.
1996///
1997/// The iterator should be finite; if it is infinite, [`Vec`]s of length 2 and above will never be
1998/// generated.
1999///
2000/// If the input iterator is infinite, the output length is also infinite.
2001///
2002/// If the input iterator length is $n$, the output length is $2^n$.
2003///
2004/// If `xs` is empty, the output consists of a single empty [`Vec`].
2005///
2006/// # Examples
2007/// ```
2008/// use itertools::Itertools;
2009/// use malachite_base::vecs::exhaustive::shortlex_ordered_unique_vecs;
2010///
2011/// let xss = shortlex_ordered_unique_vecs(1..=4).collect_vec();
2012/// assert_eq!(
2013///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2014///     &[
2015///         &[][..],
2016///         &[1],
2017///         &[2],
2018///         &[3],
2019///         &[4],
2020///         &[1, 2],
2021///         &[1, 3],
2022///         &[1, 4],
2023///         &[2, 3],
2024///         &[2, 4],
2025///         &[3, 4],
2026///         &[1, 2, 3],
2027///         &[1, 2, 4],
2028///         &[1, 3, 4],
2029///         &[2, 3, 4],
2030///         &[1, 2, 3, 4]
2031///     ]
2032/// );
2033/// ```
2034#[inline]
2035pub fn shortlex_ordered_unique_vecs<I: Clone + Iterator>(
2036    xs: I,
2037) -> ShortlexOrderedUniqueCollections<I, Vec<I::Item>>
2038where
2039    I::Item: Clone,
2040{
2041    shortlex_ordered_unique_vecs_length_inclusive_range(0, u64::MAX, xs)
2042}
2043
2044/// Generates [`Vec`]s with a mininum length, with elements from a single iterator, such that each
2045/// [`Vec`] has no repeated elements, and the elements in each [`Vec`] are ordered the same way as
2046/// they are in the source iterator.
2047///
2048/// The [`Vec`]s are generated in order of increasing length, and within each length they are
2049/// ordered lexicographically with respect to the order of the element iterator.
2050///
2051/// The source iterator should not repeat any elements, but this is not enforced.
2052///
2053/// The iterator should be finite; if it is infinite, [`Vec`]s of length `\max(2, \ell + 1)` and
2054/// above will never be generated.
2055///
2056/// If the input iterator is infinite, the output length is also infinite.
2057///
2058/// If the input iterator length is $n$ and the `min_length` is $\ell$, the output length is
2059/// $$
2060/// \sum_{i=\ell}^n \binom{n}{i}.
2061/// $$
2062///
2063/// # Examples
2064/// ```
2065/// use itertools::Itertools;
2066/// use malachite_base::vecs::exhaustive::shortlex_ordered_unique_vecs_min_length;
2067///
2068/// let xss = shortlex_ordered_unique_vecs_min_length(2, 1..=4).collect_vec();
2069/// assert_eq!(
2070///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2071///     &[
2072///         &[1, 2][..],
2073///         &[1, 3],
2074///         &[1, 4],
2075///         &[2, 3],
2076///         &[2, 4],
2077///         &[3, 4],
2078///         &[1, 2, 3],
2079///         &[1, 2, 4],
2080///         &[1, 3, 4],
2081///         &[2, 3, 4],
2082///         &[1, 2, 3, 4]
2083///     ]
2084/// );
2085/// ```
2086#[inline]
2087pub fn shortlex_ordered_unique_vecs_min_length<I: Clone + Iterator>(
2088    min_length: u64,
2089    xs: I,
2090) -> ShortlexOrderedUniqueCollections<I, Vec<I::Item>>
2091where
2092    I::Item: Clone,
2093{
2094    shortlex_ordered_unique_vecs_length_inclusive_range(min_length, u64::MAX, xs)
2095}
2096
2097/// Generates [`Vec`]s, with lengths in a range $[a, b)$, with elements from a single iterator, such
2098/// that each [`Vec`] has no repeated elements, and the elements in each [`Vec`] are ordered the
2099/// same way as they are in the source iterator.
2100///
2101/// The [`Vec`]s are generated in order of increasing length, and within each length they are
2102/// ordered lexicographically with respect to the order of the element iterator.
2103///
2104/// The source iterator should not repeat any elements, but this is not enforced.
2105///
2106/// The iterator should be finite; if it is infinite, [`Vec`]s of length `\max(2, a + 1)` and above
2107/// will never be generated.
2108///
2109/// If $a \leq b$, the output is empty.
2110///
2111/// If $a = 0$ and $b = 1$, the output consists of a single empty [`Vec`].
2112///
2113/// If the input iterator is infinite and $0 < a < b$, the output length is also infinite.
2114///
2115/// If the input iterator length is $n$, the output length is
2116/// $$
2117/// \sum_{i=a}^{b - 1} \binom{n}{i}.
2118/// $$
2119///
2120/// # Examples
2121/// ```
2122/// use itertools::Itertools;
2123/// use malachite_base::vecs::exhaustive::shortlex_ordered_unique_vecs_length_range;
2124///
2125/// let xss = shortlex_ordered_unique_vecs_length_range(2, 4, 1..=4).collect_vec();
2126/// assert_eq!(
2127///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2128///     &[
2129///         &[1, 2][..],
2130///         &[1, 3],
2131///         &[1, 4],
2132///         &[2, 3],
2133///         &[2, 4],
2134///         &[3, 4],
2135///         &[1, 2, 3],
2136///         &[1, 2, 4],
2137///         &[1, 3, 4],
2138///         &[2, 3, 4],
2139///     ]
2140/// );
2141/// ```
2142#[inline]
2143pub fn shortlex_ordered_unique_vecs_length_range<I: Clone + Iterator>(
2144    mut a: u64,
2145    mut b: u64,
2146    xs: I,
2147) -> ShortlexOrderedUniqueCollections<I, Vec<I::Item>>
2148where
2149    I::Item: Clone,
2150{
2151    if b == 0 {
2152        // Transform an empty (x, 0) range into (2, 1), which is also empty but doesn't cause
2153        // overflow
2154        a = 2;
2155        b = 1;
2156    }
2157    shortlex_ordered_unique_vecs_length_inclusive_range(a, b - 1, xs)
2158}
2159
2160/// Generates [`Vec`]s, with lengths in a range $[a, b]$, with elements from a single iterator, such
2161/// that each [`Vec`] has no repeated elements, and the elements in each [`Vec`] are ordered the
2162/// same way as they are in the source iterator.
2163///
2164/// The [`Vec`]s are generated in order of increasing length, and within each length they are
2165/// ordered lexicographically with respect to the order of the element iterator.
2166///
2167/// The source iterator should not repeat any elements, but this is not enforced.
2168///
2169/// The iterator should be finite; if it is infinite, [`Vec`]s of length `\max(2, a + 1)` and above
2170/// will never be generated.
2171///
2172/// If $a < b$, the output is empty.
2173///
2174/// If $a = b = 0$, the output consists of a single empty [`Vec`].
2175///
2176/// If the input iterator is infinite and $0 < a \leq b$, the output length is also infinite.
2177///
2178/// If the input iterator length is $n$, the output length is
2179/// $$
2180/// \sum_{i=a}^b \binom{n}{i}.
2181/// $$
2182///
2183/// # Examples
2184/// ```
2185/// use itertools::Itertools;
2186/// use malachite_base::vecs::exhaustive::shortlex_ordered_unique_vecs_length_inclusive_range;
2187///
2188/// let xss = shortlex_ordered_unique_vecs_length_inclusive_range(2, 3, 1..=4).collect_vec();
2189/// assert_eq!(
2190///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2191///     &[
2192///         &[1, 2][..],
2193///         &[1, 3],
2194///         &[1, 4],
2195///         &[2, 3],
2196///         &[2, 4],
2197///         &[3, 4],
2198///         &[1, 2, 3],
2199///         &[1, 2, 4],
2200///         &[1, 3, 4],
2201///         &[2, 3, 4],
2202///     ]
2203/// );
2204/// ```
2205#[inline]
2206pub fn shortlex_ordered_unique_vecs_length_inclusive_range<I: Clone + Iterator>(
2207    a: u64,
2208    b: u64,
2209    xs: I,
2210) -> ShortlexOrderedUniqueCollections<I, Vec<I::Item>>
2211where
2212    I::Item: Clone,
2213{
2214    ShortlexOrderedUniqueCollections::new(a, b, xs)
2215}
2216
2217/// Generates all collections of elements from an iterator in lexicographic order, where the
2218/// collections have no repetitions and are ordered the same way as in the iterator.
2219#[derive(Clone, Debug)]
2220pub struct LexOrderedUniqueCollections<I: Iterator, C: FromIterator<I::Item>>
2221where
2222    I::Item: Clone,
2223{
2224    done: bool,
2225    first: bool,
2226    min_len: usize,
2227    max_len: usize,
2228    xs: IteratorCache<I>,
2229    indices: Vec<usize>,
2230    phantom_i: PhantomData<*const I::Item>,
2231    phantom_c: PhantomData<*const C>,
2232}
2233
2234impl<I: Iterator, C: FromIterator<I::Item>> LexOrderedUniqueCollections<I, C>
2235where
2236    I::Item: Clone,
2237{
2238    pub(crate) fn new(a: u64, b: u64, xs: I) -> LexOrderedUniqueCollections<I, C> {
2239        LexOrderedUniqueCollections {
2240            done: a > b,
2241            first: true,
2242            min_len: usize::exact_from(a),
2243            max_len: usize::exact_from(b),
2244            xs: IteratorCache::new(xs),
2245            indices: (0..usize::exact_from(a)).collect(),
2246            phantom_i: PhantomData,
2247            phantom_c: PhantomData,
2248        }
2249    }
2250}
2251
2252impl<I: Iterator, C: FromIterator<I::Item>> Iterator for LexOrderedUniqueCollections<I, C>
2253where
2254    I::Item: Clone,
2255{
2256    type Item = C;
2257
2258    fn next(&mut self) -> Option<C> {
2259        if self.done {
2260            return None;
2261        }
2262        let k = self.indices.len();
2263        if self.first {
2264            self.first = false;
2265            self.xs.get(k);
2266            if let Some(n) = self.xs.known_len() {
2267                if n < k {
2268                    self.done = true;
2269                    return None;
2270                }
2271            }
2272        } else if k == 0 {
2273            if self.xs.get(0).is_none() {
2274                self.done = true;
2275                return None;
2276            }
2277            self.indices.push(0);
2278        } else {
2279            let last_i = *self.indices.last().unwrap();
2280            let next_i = last_i + 1;
2281            if k < self.max_len && self.xs.get(next_i).is_some() {
2282                // For example, if xs is [0, 1, 2, 3] and max_len is 4, then the next set of indices
2283                // after [0, 1] is [0, 1, 2].
2284                self.indices.push(next_i);
2285            } else if k == self.min_len {
2286                // For example, if xs is [0, 1, 2, 3] and min_len is 2, then the next set of indices
2287                // after [1, 3] is [2, 3].
2288                if let Some(n) = self.xs.known_len() {
2289                    if fixed_length_ordered_unique_indices_helper(n, k, &mut self.indices) {
2290                        self.done = true;
2291                        return None;
2292                    }
2293                } else {
2294                    *self.indices.last_mut().unwrap() += 1;
2295                }
2296            } else if self.xs.get(next_i).is_some() {
2297                // For example, if xs is [0, 1, 2, 3] and max_len is 3, then the next set of indices
2298                // after [1, 2, 3] is [1, 2, 4].
2299                *self.indices.last_mut().unwrap() = next_i;
2300            } else {
2301                let x = self.indices.pop();
2302                if let Some(last) = self.indices.last_mut() {
2303                    // For example, if xs is [0, 1, 2, 3] and max_len is 3, then the next set of
2304                    // indices after [0, 1, 2] is [0, 1, 3].
2305                    *last += 1;
2306                } else {
2307                    let next_x = x.unwrap() + 1;
2308                    if self.xs.get(next_x).is_none() {
2309                        // For example, if xs is [0, 1, 2, 3], then nothing comes after the indices
2310                        // [3].
2311                        self.done = true;
2312                        return None;
2313                    }
2314                    // For example, if xs is [0, 1, 2, 3] and max_len is 1, then the next set of
2315                    // indices after [0] is [1].
2316                    self.indices.push(next_x);
2317                }
2318            }
2319        }
2320        if let Some(&last_index) = self.indices.last() {
2321            // Give known len a chance to be set
2322            self.xs.get(last_index + 1);
2323        }
2324        Some(
2325            self.indices
2326                .iter()
2327                .map(|&i| self.xs.assert_get(i).clone())
2328                .collect(),
2329        )
2330    }
2331}
2332
2333/// Generates [`Vec`]s with elements from a single iterator, such that each [`Vec`] has no repeated
2334/// elements, and the elements in each [`Vec`] are ordered the same way as they are in the source
2335/// iterator.
2336///
2337/// The [`Vec`]s are ordered lexicographically with respect to the order of the element iterator.
2338///
2339/// The source iterator should not repeat any elements, but this is not enforced.
2340///
2341/// The iterator should be finite; if it is infinite, only prefixes of the iterator will be
2342/// generated.
2343///
2344/// If the input iterator is infinite, the output length is also infinite.
2345///
2346/// If the input iterator length is $n$, the output length is $2^n$.
2347///
2348/// If `xs` is empty, the output consists of a single empty [`Vec`].
2349///
2350/// # Examples
2351/// ```
2352/// use itertools::Itertools;
2353/// use malachite_base::vecs::exhaustive::lex_ordered_unique_vecs;
2354///
2355/// let xss = lex_ordered_unique_vecs(1..=4).collect_vec();
2356/// assert_eq!(
2357///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2358///     &[
2359///         &[][..],
2360///         &[1],
2361///         &[1, 2],
2362///         &[1, 2, 3],
2363///         &[1, 2, 3, 4],
2364///         &[1, 2, 4],
2365///         &[1, 3],
2366///         &[1, 3, 4],
2367///         &[1, 4],
2368///         &[2],
2369///         &[2, 3],
2370///         &[2, 3, 4],
2371///         &[2, 4],
2372///         &[3],
2373///         &[3, 4],
2374///         &[4]
2375///     ]
2376/// );
2377/// ```
2378#[inline]
2379pub fn lex_ordered_unique_vecs<I: Clone + Iterator>(
2380    xs: I,
2381) -> LexOrderedUniqueCollections<I, Vec<I::Item>>
2382where
2383    I::Item: Clone,
2384{
2385    lex_ordered_unique_vecs_length_inclusive_range(0, u64::MAX, xs)
2386}
2387
2388/// Generates [`Vec`]s with a mininum length, with elements from a single iterator, such that each
2389/// [`Vec`] has no repeated elements, and the elements in each [`Vec`] are ordered the same way as
2390/// they are in the source iterator.
2391///
2392/// The [`Vec`]s are ordered lexicographically with respect to the order of the element iterator.
2393///
2394/// The source iterator should not repeat any elements, but this is not enforced.
2395///
2396/// The iterator should be finite; if it is infinite, only prefixes of the iterator will be
2397/// generated.
2398///
2399/// If the input iterator is infinite, the output length is also infinite.
2400///
2401/// If the input iterator length is $n$ and the `min_length` is $\ell$, the output length is
2402/// $$
2403/// \sum_{i=\ell}^n \binom{n}{i}.
2404/// $$
2405///
2406/// # Examples
2407/// ```
2408/// use itertools::Itertools;
2409/// use malachite_base::vecs::exhaustive::lex_ordered_unique_vecs_min_length;
2410///
2411/// let xss = lex_ordered_unique_vecs_min_length(2, 1..=4).collect_vec();
2412/// assert_eq!(
2413///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2414///     &[
2415///         &[1, 2][..],
2416///         &[1, 2, 3],
2417///         &[1, 2, 3, 4],
2418///         &[1, 2, 4],
2419///         &[1, 3],
2420///         &[1, 3, 4],
2421///         &[1, 4],
2422///         &[2, 3],
2423///         &[2, 3, 4],
2424///         &[2, 4],
2425///         &[3, 4],
2426///     ]
2427/// );
2428/// ```
2429#[inline]
2430pub fn lex_ordered_unique_vecs_min_length<I: Clone + Iterator>(
2431    min_length: u64,
2432    xs: I,
2433) -> LexOrderedUniqueCollections<I, Vec<I::Item>>
2434where
2435    I::Item: Clone,
2436{
2437    lex_ordered_unique_vecs_length_inclusive_range(min_length, u64::MAX, xs)
2438}
2439
2440/// Generates [`Vec`]s, with lengths in a range $[a, b)$, with elements from a single iterator, such
2441/// that each [`Vec`] has no repeated elements, and the elements in each [`Vec`] are ordered the
2442/// same way as they are in the source iterator.
2443///
2444/// The [`Vec`]s are ordered lexicographically with respect to the order of the element iterator.
2445///
2446/// The source iterator should not repeat any elements, but this is not enforced.
2447///
2448/// The iterator should be finite; if it is infinite, only prefixes of the iterator will be
2449/// generated.
2450///
2451/// If $a \leq b$, the output is empty.
2452///
2453/// If $a = 0$ and $b = 1$, the output consists of a single empty [`Vec`].
2454///
2455/// If the input iterator is infinite and $0 < a < b$, the output length is also infinite.
2456///
2457/// If the input iterator length is $n$, the output length is
2458/// $$
2459/// \sum_{i=a}^{b - 1} \binom{n}{i}.
2460/// $$
2461///
2462/// # Examples
2463/// ```
2464/// use itertools::Itertools;
2465/// use malachite_base::vecs::exhaustive::lex_ordered_unique_vecs_length_range;
2466///
2467/// let xss = lex_ordered_unique_vecs_length_range(2, 4, 1..=4).collect_vec();
2468/// assert_eq!(
2469///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2470///     &[
2471///         &[1, 2][..],
2472///         &[1, 2, 3],
2473///         &[1, 2, 4],
2474///         &[1, 3],
2475///         &[1, 3, 4],
2476///         &[1, 4],
2477///         &[2, 3],
2478///         &[2, 3, 4],
2479///         &[2, 4],
2480///         &[3, 4],
2481///     ]
2482/// );
2483/// ```
2484#[inline]
2485pub fn lex_ordered_unique_vecs_length_range<I: Clone + Iterator>(
2486    mut a: u64,
2487    mut b: u64,
2488    xs: I,
2489) -> LexOrderedUniqueCollections<I, Vec<I::Item>>
2490where
2491    I::Item: Clone,
2492{
2493    if b == 0 {
2494        // Transform an empty (x, 0) range into (2, 1), which is also empty but doesn't cause
2495        // overflow
2496        a = 2;
2497        b = 1;
2498    }
2499    lex_ordered_unique_vecs_length_inclusive_range(a, b - 1, xs)
2500}
2501
2502/// Generates [`Vec`]s, with lengths in a range $[a, b]$, with elements from a single iterator, such
2503/// that each [`Vec`] has no repeated elements, and the elements in each [`Vec`] are ordered the
2504/// same way as they are in the source iterator.
2505///
2506/// The [`Vec`]s are ordered lexicographically with respect to the order of the element iterator.
2507///
2508/// The source iterator should not repeat any elements, but this is not enforced.
2509///
2510/// The iterator should be finite; if it is infinite, only prefixes of the iterator will be
2511/// generated.
2512///
2513/// If $a < b$, the output is empty.
2514///
2515/// If $a = b = 0$, the output consists of a single empty [`Vec`].
2516///
2517/// If the input iterator is infinite and $0 < a \leq b$, the output length is also infinite.
2518///
2519/// If the input iterator length is $n$, the output length is
2520/// $$
2521/// \sum_{i=a}^b \binom{n}{i}.
2522/// $$
2523///
2524/// # Examples
2525/// ```
2526/// use itertools::Itertools;
2527/// use malachite_base::vecs::exhaustive::lex_ordered_unique_vecs_length_inclusive_range;
2528///
2529/// let xss = lex_ordered_unique_vecs_length_inclusive_range(2, 3, 1..=4).collect_vec();
2530/// assert_eq!(
2531///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2532///     &[
2533///         &[1, 2][..],
2534///         &[1, 2, 3],
2535///         &[1, 2, 4],
2536///         &[1, 3],
2537///         &[1, 3, 4],
2538///         &[1, 4],
2539///         &[2, 3],
2540///         &[2, 3, 4],
2541///         &[2, 4],
2542///         &[3, 4],
2543///     ]
2544/// );
2545/// ```
2546#[inline]
2547pub fn lex_ordered_unique_vecs_length_inclusive_range<I: Clone + Iterator>(
2548    a: u64,
2549    b: u64,
2550    xs: I,
2551) -> LexOrderedUniqueCollections<I, Vec<I::Item>>
2552where
2553    I::Item: Clone,
2554{
2555    LexOrderedUniqueCollections::new(a, b, xs)
2556}
2557
2558/// This function is used for iterating through all bit patterns with a specified number of minimum
2559/// and maximum `true` bits.
2560///
2561/// Given an existing bit pattern, and a reference `bit_count`, which must equal the number of
2562/// `true`s in the pattern, mutates the pattern into the next pattern with a valid number of `true`
2563/// bits. See the unit tests for many examples.
2564///
2565/// # Worst-case complexity
2566/// $$
2567/// T(k) = O(k)
2568/// $$
2569///
2570/// $$
2571/// M(k) = O(k)
2572/// $$
2573///
2574/// where $T$ is time, $M$ is additional memory, and $k$ is the length of `pattern`. The memory
2575/// usage is only linear when the pattern vector needs to be reallocated, which happens rarely.
2576///
2577/// # Panics
2578/// Panics if `max_bits` is zero. (However, `min_bits` may be zero.)
2579///
2580/// # Examples
2581/// ```
2582/// use malachite_base::vecs::exhaustive::next_bit_pattern;
2583///
2584/// // Suppose we are generating all bit patterns with 2 to 4 true bits, inclusive. Suppose our
2585/// // current pattern is `1111000`. Then, the lexicographically next largest valid pattern is
2586/// // `10000001`. (All patterns of the form `1111xxx`, where the `x`s are not all zero, have too
2587/// // many ones. That brings us to `10000000`, which has too few ones, and then `10000001`.)
2588/// //
2589/// // The patterns are represented "in reverse", with least-significant bits appearing first.
2590/// let mut pattern = vec![false, false, false, true, true, true, true];
2591/// let mut bit_count = 4;
2592/// next_bit_pattern(&mut pattern, &mut bit_count, 2, 4);
2593/// assert_eq!(
2594///     pattern,
2595///     &[true, false, false, false, false, false, false, true]
2596/// );
2597/// assert_eq!(bit_count, 2);
2598/// ```
2599pub fn next_bit_pattern(
2600    pattern: &mut Vec<bool>,
2601    bit_count: &mut usize,
2602    min_bits: usize,
2603    max_bits: usize,
2604) {
2605    assert_ne!(max_bits, 0);
2606    match pattern.first() {
2607        None => {
2608            pattern.push(true);
2609            *bit_count = 1;
2610        }
2611        Some(&false) => {
2612            if *bit_count < max_bits {
2613                pattern[0] = true;
2614                *bit_count += 1;
2615            } else {
2616                let leading_false_count = pattern.iter().take_while(|&&b| !b).count();
2617                let true_after_false_count = pattern[leading_false_count..]
2618                    .iter()
2619                    .take_while(|&&b| b)
2620                    .count();
2621                let tf_count = leading_false_count + true_after_false_count;
2622                if tf_count == pattern.len() {
2623                    for b in &mut *pattern {
2624                        *b = false;
2625                    }
2626                    pattern.push(true);
2627                    *bit_count = 1;
2628                } else {
2629                    for b in &mut pattern[leading_false_count..tf_count] {
2630                        *b = false;
2631                    }
2632                    pattern[tf_count] = true;
2633                    *bit_count -= true_after_false_count - 1;
2634                }
2635                if *bit_count < min_bits {
2636                    let diff = min_bits - *bit_count;
2637                    for b in &mut pattern[..diff] {
2638                        *b = true;
2639                    }
2640                    *bit_count += diff;
2641                }
2642            }
2643        }
2644        Some(&true) => {
2645            let leading_true_count = pattern.iter().take_while(|&&b| b).count();
2646            for b in &mut pattern[..leading_true_count] {
2647                *b = false;
2648            }
2649            if leading_true_count == pattern.len() {
2650                pattern.push(true);
2651            } else {
2652                pattern[leading_true_count] = true;
2653            }
2654            *bit_count -= leading_true_count - 1;
2655            if *bit_count < min_bits {
2656                let diff = min_bits - *bit_count;
2657                for b in &mut pattern[..diff] {
2658                    *b = true;
2659                }
2660                *bit_count += diff;
2661            }
2662        }
2663    }
2664}
2665
2666#[derive(Clone)]
2667#[doc(hidden)]
2668pub struct ExhaustiveOrderedUniqueCollectionsGreaterThanOne<I: Iterator, C: FromIterator<I::Item>>
2669where
2670    I::Item: Clone,
2671{
2672    done: bool,
2673    first: bool,
2674    min_bits: usize,
2675    max_bits: usize,
2676    xs: IteratorCache<I>,
2677    pattern: Vec<bool>,
2678    bit_count: usize,
2679    phantom: PhantomData<*const C>,
2680}
2681
2682impl<I: Iterator, C: FromIterator<I::Item>> Iterator
2683    for ExhaustiveOrderedUniqueCollectionsGreaterThanOne<I, C>
2684where
2685    I::Item: Clone,
2686{
2687    type Item = C;
2688
2689    fn next(&mut self) -> Option<C> {
2690        if self.done {
2691            return None;
2692        } else if self.first {
2693            self.first = false;
2694        } else {
2695            next_bit_pattern(
2696                &mut self.pattern,
2697                &mut self.bit_count,
2698                self.min_bits,
2699                self.max_bits,
2700            );
2701        }
2702        if !self.pattern.is_empty() && self.xs.get(self.pattern.len() - 1).is_none() {
2703            self.done = true;
2704            return None;
2705        }
2706        Some(
2707            self.pattern
2708                .iter()
2709                .enumerate()
2710                .filter_map(|(i, &b)| {
2711                    if b {
2712                        Some(self.xs.assert_get(i).clone())
2713                    } else {
2714                        None
2715                    }
2716                })
2717                .collect(),
2718        )
2719    }
2720}
2721
2722/// Generates all collections of elements from an iterator, where the collections have no
2723/// repetitions and are ordered the same way as in the iterator.
2724#[derive(Clone)]
2725pub enum ExhaustiveOrderedUniqueCollections<I: Iterator, C: FromIterator<I::Item>>
2726where
2727    I::Item: Clone,
2728{
2729    None,
2730    Zero(bool),
2731    ZeroOne(bool, I),
2732    One(I),
2733    GreaterThanOne(ExhaustiveOrderedUniqueCollectionsGreaterThanOne<I, C>),
2734}
2735
2736impl<I: Iterator, C: FromIterator<I::Item>> ExhaustiveOrderedUniqueCollections<I, C>
2737where
2738    I::Item: Clone,
2739{
2740    pub(crate) fn new(a: u64, b: u64, xs: I) -> ExhaustiveOrderedUniqueCollections<I, C> {
2741        match (a, b) {
2742            (a, b) if a > b => ExhaustiveOrderedUniqueCollections::None,
2743            (0, 0) => ExhaustiveOrderedUniqueCollections::Zero(false),
2744            (0, 1) => ExhaustiveOrderedUniqueCollections::ZeroOne(true, xs),
2745            (1, 1) => ExhaustiveOrderedUniqueCollections::One(xs),
2746            (a, b) => ExhaustiveOrderedUniqueCollections::GreaterThanOne(
2747                ExhaustiveOrderedUniqueCollectionsGreaterThanOne {
2748                    done: false,
2749                    first: true,
2750                    min_bits: usize::saturating_from(a),
2751                    max_bits: usize::saturating_from(b),
2752                    xs: IteratorCache::new(xs),
2753                    pattern: vec![true; usize::saturating_from(a)],
2754                    bit_count: usize::saturating_from(a),
2755                    phantom: PhantomData,
2756                },
2757            ),
2758        }
2759    }
2760}
2761
2762impl<I: Iterator, C: FromIterator<I::Item>> Iterator for ExhaustiveOrderedUniqueCollections<I, C>
2763where
2764    I::Item: Clone,
2765{
2766    type Item = C;
2767
2768    fn next(&mut self) -> Option<C> {
2769        match self {
2770            ExhaustiveOrderedUniqueCollections::None => None,
2771            ExhaustiveOrderedUniqueCollections::Zero(done) => {
2772                if *done {
2773                    None
2774                } else {
2775                    *done = true;
2776                    Some(empty().collect())
2777                }
2778            }
2779            ExhaustiveOrderedUniqueCollections::ZeroOne(first, xs) => {
2780                if *first {
2781                    *first = false;
2782                    Some(empty().collect())
2783                } else {
2784                    xs.next().map(|x| once(x).collect())
2785                }
2786            }
2787            ExhaustiveOrderedUniqueCollections::One(xs) => xs.next().map(|x| once(x).collect()),
2788            ExhaustiveOrderedUniqueCollections::GreaterThanOne(xs) => xs.next(),
2789        }
2790    }
2791}
2792
2793/// Generates [`Vec`]s of a given length with elements from a single iterator, such that each
2794/// [`Vec`] has no repeated elements, and the elements in each [`Vec`] are ordered the same way as
2795/// they are in the source iterator.
2796///
2797/// The source iterator should not repeat any elements, but this is not enforced.
2798///
2799/// If $k$ is 0, the output length is 1.
2800///
2801/// If $k$ is nonzero and the input iterator is infinite, the output length is also infinite.
2802///
2803/// If $k$ is nonzero and the input iterator length is $n$, the output length is $\binom{n}{k}$.
2804///
2805/// If $k$ is 0, the output consists of one empty [`Vec`].
2806///
2807/// If `xs` is empty, the output is also empty, unless $k$ is 0.
2808///
2809/// # Examples
2810/// ```
2811/// use itertools::Itertools;
2812/// use malachite_base::vecs::exhaustive::exhaustive_ordered_unique_vecs_fixed_length;
2813///
2814/// let xss = exhaustive_ordered_unique_vecs_fixed_length(4, 1..=6).collect_vec();
2815/// assert_eq!(
2816///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2817///     &[
2818///         &[1, 2, 3, 4],
2819///         &[1, 2, 3, 5],
2820///         &[1, 2, 4, 5],
2821///         &[1, 3, 4, 5],
2822///         &[2, 3, 4, 5],
2823///         &[1, 2, 3, 6],
2824///         &[1, 2, 4, 6],
2825///         &[1, 3, 4, 6],
2826///         &[2, 3, 4, 6],
2827///         &[1, 2, 5, 6],
2828///         &[1, 3, 5, 6],
2829///         &[2, 3, 5, 6],
2830///         &[1, 4, 5, 6],
2831///         &[2, 4, 5, 6],
2832///         &[3, 4, 5, 6]
2833///     ]
2834/// );
2835/// ```
2836#[inline]
2837pub fn exhaustive_ordered_unique_vecs_fixed_length<I: Iterator>(
2838    k: u64,
2839    xs: I,
2840) -> ExhaustiveOrderedUniqueCollections<I, Vec<I::Item>>
2841where
2842    I::Item: Clone,
2843{
2844    exhaustive_ordered_unique_vecs_length_inclusive_range(k, k, xs)
2845}
2846
2847/// Generates [`Vec`]s with elements from a single iterator, such that each [`Vec`] has no repeated
2848/// elements, and the elements in each [`Vec`] are ordered the same way as they are in the source
2849/// iterator.
2850///
2851/// The source iterator should not repeat any elements, but this is not enforced.
2852///
2853/// The iterator should be finite; if it is infinite, only prefixes of the iterator will be
2854/// generated.
2855///
2856/// If the input iterator is infinite, the output length is also infinite.
2857///
2858/// If the input iterator length is $n$, the output length is $2^n$.
2859///
2860/// If `xs` is empty, the output consists of a single empty [`Vec`].
2861///
2862/// # Examples
2863/// ```
2864/// use itertools::Itertools;
2865/// use malachite_base::vecs::exhaustive::exhaustive_ordered_unique_vecs;
2866///
2867/// let xss = exhaustive_ordered_unique_vecs(1..=4).collect_vec();
2868/// assert_eq!(
2869///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2870///     &[
2871///         &[][..],
2872///         &[1],
2873///         &[2],
2874///         &[1, 2],
2875///         &[3],
2876///         &[1, 3],
2877///         &[2, 3],
2878///         &[1, 2, 3],
2879///         &[4],
2880///         &[1, 4],
2881///         &[2, 4],
2882///         &[1, 2, 4],
2883///         &[3, 4],
2884///         &[1, 3, 4],
2885///         &[2, 3, 4],
2886///         &[1, 2, 3, 4]
2887///     ]
2888/// );
2889/// ```
2890#[inline]
2891pub fn exhaustive_ordered_unique_vecs<I: Iterator>(
2892    xs: I,
2893) -> ExhaustiveOrderedUniqueCollections<I, Vec<I::Item>>
2894where
2895    I::Item: Clone,
2896{
2897    exhaustive_ordered_unique_vecs_length_inclusive_range(0, u64::MAX, xs)
2898}
2899
2900/// Generates [`Vec`]s with a mininum length, with elements from a single iterator, such that each
2901/// [`Vec`] has no repeated elements, and the elements in each [`Vec`] are ordered the same way as
2902/// they are in the source iterator.
2903///
2904/// The source iterator should not repeat any elements, but this is not enforced.
2905///
2906/// The iterator should be finite; if it is infinite, only prefixes of the iterator will be
2907/// generated.
2908///
2909/// If the input iterator is infinite, the output length is also infinite.
2910///
2911/// If the input iterator length is $n$ and the `min_length` is $\ell$, the output length is
2912/// $$
2913/// \sum_{i=\ell}^n \binom{n}{i}.
2914/// $$
2915///
2916/// # Examples
2917/// ```
2918/// use itertools::Itertools;
2919/// use malachite_base::vecs::exhaustive::exhaustive_ordered_unique_vecs_min_length;
2920///
2921/// let xss = exhaustive_ordered_unique_vecs_min_length(2, 1..=4).collect_vec();
2922/// assert_eq!(
2923///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2924///     &[
2925///         &[1, 2][..],
2926///         &[1, 3],
2927///         &[2, 3],
2928///         &[1, 2, 3],
2929///         &[1, 4],
2930///         &[2, 4],
2931///         &[1, 2, 4],
2932///         &[3, 4],
2933///         &[1, 3, 4],
2934///         &[2, 3, 4],
2935///         &[1, 2, 3, 4]
2936///     ]
2937/// );
2938/// ```
2939#[inline]
2940pub fn exhaustive_ordered_unique_vecs_min_length<I: Iterator>(
2941    min_length: u64,
2942    xs: I,
2943) -> ExhaustiveOrderedUniqueCollections<I, Vec<I::Item>>
2944where
2945    I::Item: Clone,
2946{
2947    exhaustive_ordered_unique_vecs_length_inclusive_range(min_length, u64::MAX, xs)
2948}
2949
2950/// Generates [`Vec`]s, with lengths in a range $[a, b)$, with elements from a single iterator, such
2951/// that each [`Vec`] has no repeated elements, and the elements in each [`Vec`] are ordered the
2952/// same way as they are in the source iterator.
2953///
2954/// The source iterator should not repeat any elements, but this is not enforced.
2955///
2956/// The iterator should be finite; if it is infinite, only prefixes of the iterator will be
2957/// generated.
2958///
2959/// If $a \leq b$, the output is empty.
2960///
2961/// If $a = 0$ and $b = 1$, the output consists of a single empty [`Vec`].
2962///
2963/// If the input iterator is infinite and $0 < a < b$, the output length is also infinite.
2964///
2965/// If the input iterator length is $n$, the output length is
2966/// $$
2967/// \sum_{i=a}^{b - 1} \binom{n}{i}.
2968/// $$
2969///
2970/// # Examples
2971/// ```
2972/// use itertools::Itertools;
2973/// use malachite_base::vecs::exhaustive::exhaustive_ordered_unique_vecs_length_range;
2974///
2975/// let xss = exhaustive_ordered_unique_vecs_length_range(2, 4, 1..=4).collect_vec();
2976/// assert_eq!(
2977///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2978///     &[
2979///         &[1, 2][..],
2980///         &[1, 3],
2981///         &[2, 3],
2982///         &[1, 2, 3],
2983///         &[1, 4],
2984///         &[2, 4],
2985///         &[1, 2, 4],
2986///         &[3, 4],
2987///         &[1, 3, 4],
2988///         &[2, 3, 4]
2989///     ]
2990/// );
2991/// ```
2992#[inline]
2993pub fn exhaustive_ordered_unique_vecs_length_range<I: Iterator>(
2994    a: u64,
2995    b: u64,
2996    xs: I,
2997) -> ExhaustiveOrderedUniqueCollections<I, Vec<I::Item>>
2998where
2999    I::Item: Clone,
3000{
3001    if a >= b {
3002        ExhaustiveOrderedUniqueCollections::None
3003    } else {
3004        exhaustive_ordered_unique_vecs_length_inclusive_range(a, b - 1, xs)
3005    }
3006}
3007
3008/// Generates [`Vec`]s, with lengths in a range $[a, b]$, with elements from a single iterator, such
3009/// that each [`Vec`] has no repeated elements, and the elements in each [`Vec`] are ordered the
3010/// same way as they are in the source iterator.
3011///
3012/// The [`Vec`]s are ordered lexicographically with respect to the order of the element iterator.
3013///
3014/// The source iterator should not repeat any elements, but this is not enforced.
3015///
3016/// The iterator should be finite; if it is infinite, only prefixes of the iterator will be
3017/// generated.
3018///
3019/// If $a < b$, the output is empty.
3020///
3021/// If $a = b = 0$, the output consists of a single empty [`Vec`].
3022///
3023/// If the input iterator is infinite and $0 < a \leq b$, the output length is also infinite.
3024///
3025/// If the input iterator length is $n$, the output length is
3026/// $$
3027/// \sum_{i=a}^b \binom{n}{i}.
3028/// $$
3029///
3030/// # Examples
3031/// ```
3032/// use itertools::Itertools;
3033/// use malachite_base::vecs::exhaustive::exhaustive_ordered_unique_vecs_length_inclusive_range;
3034///
3035/// let xss = exhaustive_ordered_unique_vecs_length_inclusive_range(2, 3, 1..=4).collect_vec();
3036/// assert_eq!(
3037///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
3038///     &[
3039///         &[1, 2][..],
3040///         &[1, 3],
3041///         &[2, 3],
3042///         &[1, 2, 3],
3043///         &[1, 4],
3044///         &[2, 4],
3045///         &[1, 2, 4],
3046///         &[3, 4],
3047///         &[1, 3, 4],
3048///         &[2, 3, 4]
3049///     ]
3050/// );
3051/// ```
3052#[inline]
3053pub fn exhaustive_ordered_unique_vecs_length_inclusive_range<I: Iterator>(
3054    a: u64,
3055    b: u64,
3056    xs: I,
3057) -> ExhaustiveOrderedUniqueCollections<I, Vec<I::Item>>
3058where
3059    I::Item: Clone,
3060{
3061    ExhaustiveOrderedUniqueCollections::new(a, b, xs)
3062}
3063
3064fn fixed_length_unique_indices_helper(indices: &mut [usize], used: &mut [bool]) -> bool {
3065    let n = used.len();
3066    let k = indices.len();
3067    assert!(k <= n);
3068    for i in (0..k).rev() {
3069        let x = indices[i];
3070        used[x] = false;
3071        for y in x + 1..n {
3072            if !used[y] {
3073                indices[i] = y;
3074                used[y] = true;
3075                let mut p = 0;
3076                for j in &mut indices[i + 1..k] {
3077                    while used[p] {
3078                        p += 1;
3079                    }
3080                    *j = p;
3081                    used[p] = true;
3082                }
3083                return false;
3084            }
3085        }
3086    }
3087    true
3088}
3089
3090#[doc(hidden)]
3091#[derive(Clone, Debug)]
3092pub struct UniqueIndices {
3093    pub done: bool,
3094    first: bool,
3095    indices: Vec<usize>,
3096    pub used: Vec<bool>,
3097}
3098
3099impl UniqueIndices {
3100    #[doc(hidden)]
3101    pub fn get_n(&self) -> usize {
3102        self.used.len()
3103    }
3104
3105    #[doc(hidden)]
3106    pub fn increment_n(&mut self) {
3107        self.used.push(false);
3108    }
3109}
3110
3111impl Iterator for UniqueIndices {
3112    type Item = Vec<usize>;
3113
3114    fn next(&mut self) -> Option<Vec<usize>> {
3115        if self.done {
3116            None
3117        } else if self.first {
3118            self.first = false;
3119            Some(self.indices.clone())
3120        } else if fixed_length_unique_indices_helper(&mut self.indices, &mut self.used) {
3121            self.done = true;
3122            None
3123        } else {
3124            Some(self.indices.clone())
3125        }
3126    }
3127}
3128
3129#[doc(hidden)]
3130pub fn unique_indices(n: usize, k: usize) -> UniqueIndices {
3131    UniqueIndices {
3132        done: n == 0 && k != 0,
3133        first: true,
3134        indices: (0..k).collect_vec(),
3135        used: repeat_n(true, k)
3136            .chain(repeat_n(false, n - k))
3137            .collect_vec(),
3138    }
3139}
3140
3141/// Generates all [`Vec`]s of elements from an iterator, where the [`Vec`]s are of a fixed length
3142/// and have no repetitions.
3143#[derive(Clone)]
3144pub struct LexUniqueVecsFixedLength<I: Iterator>
3145where
3146    I::Item: Clone,
3147{
3148    first: bool,
3149    xs: IteratorCache<I>,
3150    indices: UniqueIndices,
3151}
3152
3153impl<I: Iterator> Iterator for LexUniqueVecsFixedLength<I>
3154where
3155    I::Item: Clone,
3156{
3157    type Item = Vec<I::Item>;
3158
3159    fn next(&mut self) -> Option<Self::Item> {
3160        if self.first {
3161            if !self.indices.used.is_empty() && self.xs.get(self.indices.get_n() - 1).is_none() {
3162                self.indices.done = true;
3163            }
3164            self.first = false;
3165        }
3166        if self.xs.get(self.indices.get_n()).is_some() {
3167            self.indices.increment_n();
3168        }
3169        self.indices.next().map(|indices| {
3170            indices
3171                .into_iter()
3172                .map(|i| self.xs.assert_get(i).clone())
3173                .collect_vec()
3174        })
3175    }
3176}
3177
3178/// Generates [`Vec`]s of a given length with elements from a single iterator, such that each
3179/// [`Vec`] has no repeated elements.
3180///
3181/// The source iterator should not repeat any elements, but this is not enforced.
3182///
3183/// The order is lexicographic with respect to the order of the element iterator.
3184///
3185/// If $k$ is 0, the output length is 1.
3186///
3187/// If $k$ is nonzero and the input iterator is infinite, the output length is also infinite.
3188///
3189/// If $k$ is nonzero and the input iterator length is $n$, the output length is
3190/// $$
3191/// (n)_ k = \prod_ {i=0}^{k-1}(n - i) = frac{n!}{(n-k)!}.
3192/// $$
3193///
3194/// If $k$ is 0, the output consists of one empty [`Vec`].
3195///
3196/// If `xs` is empty, the output is also empty, unless $k$ is 0.
3197///
3198/// # Examples
3199/// ```
3200/// use itertools::Itertools;
3201/// use malachite_base::vecs::exhaustive::lex_unique_vecs_fixed_length;
3202///
3203/// let xss = lex_unique_vecs_fixed_length(4, 1..=6)
3204///     .take(20)
3205///     .collect_vec();
3206/// assert_eq!(
3207///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
3208///     &[
3209///         &[1, 2, 3, 4],
3210///         &[1, 2, 3, 5],
3211///         &[1, 2, 3, 6],
3212///         &[1, 2, 4, 3],
3213///         &[1, 2, 4, 5],
3214///         &[1, 2, 4, 6],
3215///         &[1, 2, 5, 3],
3216///         &[1, 2, 5, 4],
3217///         &[1, 2, 5, 6],
3218///         &[1, 2, 6, 3],
3219///         &[1, 2, 6, 4],
3220///         &[1, 2, 6, 5],
3221///         &[1, 3, 2, 4],
3222///         &[1, 3, 2, 5],
3223///         &[1, 3, 2, 6],
3224///         &[1, 3, 4, 2],
3225///         &[1, 3, 4, 5],
3226///         &[1, 3, 4, 6],
3227///         &[1, 3, 5, 2],
3228///         &[1, 3, 5, 4],
3229///     ]
3230/// );
3231/// ```
3232#[inline]
3233pub fn lex_unique_vecs_fixed_length<I: Iterator>(k: u64, xs: I) -> LexUniqueVecsFixedLength<I>
3234where
3235    I::Item: Clone,
3236{
3237    let k = usize::exact_from(k);
3238    LexUniqueVecsFixedLength {
3239        first: true,
3240        xs: IteratorCache::new(xs),
3241        // Initial n is k, but will grow to reach actual n (or forever, if n is infinite)
3242        indices: unique_indices(k, k),
3243    }
3244}
3245
3246/// Generates all [`Vec`]s of elements from an iterator in shortlex order, where the [`Vec`]s have
3247/// no repetitions.
3248#[derive(Clone)]
3249pub struct ShortlexUniqueVecs<I: Clone + Iterator>
3250where
3251    I::Item: Clone,
3252{
3253    current_len: u64,
3254    max_len: u64,
3255    xs: I,
3256    current_xss: LexUniqueVecsFixedLength<I>,
3257}
3258
3259impl<I: Clone + Iterator> ShortlexUniqueVecs<I>
3260where
3261    I::Item: Clone,
3262{
3263    fn new(a: u64, b: u64, xs: I) -> ShortlexUniqueVecs<I> {
3264        ShortlexUniqueVecs {
3265            current_len: a,
3266            max_len: b,
3267            xs: xs.clone(),
3268            current_xss: lex_unique_vecs_fixed_length(a, xs),
3269        }
3270    }
3271}
3272
3273impl<I: Clone + Iterator> Iterator for ShortlexUniqueVecs<I>
3274where
3275    I::Item: Clone,
3276{
3277    type Item = Vec<I::Item>;
3278
3279    fn next(&mut self) -> Option<Vec<I::Item>> {
3280        if self.current_len > self.max_len {
3281            return None;
3282        }
3283        if let Some(next) = self.current_xss.next() {
3284            Some(next)
3285        } else {
3286            self.current_len += 1;
3287            if self.current_len > self.max_len {
3288                return None;
3289            }
3290            self.current_xss = lex_unique_vecs_fixed_length(self.current_len, self.xs.clone());
3291            if let Some(next) = self.current_xss.next() {
3292                Some(next)
3293            } else {
3294                // Prevent any further iteration
3295                self.max_len = 0;
3296                self.current_len = 1;
3297                None
3298            }
3299        }
3300    }
3301}
3302
3303/// Generates [`Vec`]s with elements from a single iterator, such that each [`Vec`] has no repeated
3304/// elements.
3305///
3306/// The [`Vec`]s are generated in order of increasing length, and within each length they are
3307/// ordered lexicographically with respect to the order of the element iterator.
3308///
3309/// The source iterator should not repeat any elements, but this is not enforced.
3310///
3311/// The iterator should be finite; if it is infinite, [`Vec`]s of length 2 and above will never be
3312/// generated.
3313///
3314/// If the input iterator is infinite, the output length is also infinite.
3315///
3316/// If the input iterator length is $n$, the output length is
3317/// $$
3318/// \sum_ {k=0}^n \frac{n!}{k!}
3319/// $$
3320/// $$
3321/// = \\begin{cases}
3322///     1 & \text{if} \\quad n = 0, \\\\
3323///     2 & \text{if} \\quad n = 1, \\\\
3324///     \operatorname{round}(en!) & \\text{otherwise}.
3325/// \\end{cases}
3326/// $$
3327///
3328/// See <https://oeis.org/A000522>.
3329///
3330/// If `xs` is empty, the output consists of a single empty [`Vec`].
3331///
3332/// # Examples
3333/// ```
3334/// use itertools::Itertools;
3335/// use malachite_base::vecs::exhaustive::shortlex_unique_vecs;
3336///
3337/// let xss = shortlex_unique_vecs(1..=4).take(20).collect_vec();
3338/// assert_eq!(
3339///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
3340///     &[
3341///         &[][..],
3342///         &[1],
3343///         &[2],
3344///         &[3],
3345///         &[4],
3346///         &[1, 2],
3347///         &[1, 3],
3348///         &[1, 4],
3349///         &[2, 1],
3350///         &[2, 3],
3351///         &[2, 4],
3352///         &[3, 1],
3353///         &[3, 2],
3354///         &[3, 4],
3355///         &[4, 1],
3356///         &[4, 2],
3357///         &[4, 3],
3358///         &[1, 2, 3],
3359///         &[1, 2, 4],
3360///         &[1, 3, 2]
3361///     ]
3362/// );
3363/// ```
3364#[inline]
3365pub fn shortlex_unique_vecs<I: Clone + Iterator>(xs: I) -> ShortlexUniqueVecs<I>
3366where
3367    I::Item: Clone,
3368{
3369    shortlex_unique_vecs_length_inclusive_range(0, u64::MAX, xs)
3370}
3371
3372/// Generates [`Vec`]s with a mininum length, with elements from a single iterator, such that each
3373/// [`Vec`] has no repeated elements.
3374///
3375/// The [`Vec`]s are generated in order of increasing length, and within each length they are
3376/// ordered lexicographically with respect to the order of the element iterator.
3377///
3378/// The source iterator should not repeat any elements, but this is not enforced.
3379///
3380/// The iterator should be finite; if it is infinite, [`Vec`]s of length `\max(2, \ell + 1)` and
3381/// above will never be generated.
3382///
3383/// If the input iterator is infinite, the output length is also infinite.
3384///
3385/// If the input iterator length is $n$ and the `min_length` is $\ell$, the output length is
3386/// $$
3387/// \sum_ {k=\ell}^n \frac{n!}{k!}.
3388/// $$
3389///
3390/// # Examples
3391/// ```
3392/// use itertools::Itertools;
3393/// use malachite_base::vecs::exhaustive::shortlex_unique_vecs_min_length;
3394///
3395/// let xss = shortlex_unique_vecs_min_length(2, 1..=4)
3396///     .take(20)
3397///     .collect_vec();
3398/// assert_eq!(
3399///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
3400///     &[
3401///         &[1, 2][..],
3402///         &[1, 3],
3403///         &[1, 4],
3404///         &[2, 1],
3405///         &[2, 3],
3406///         &[2, 4],
3407///         &[3, 1],
3408///         &[3, 2],
3409///         &[3, 4],
3410///         &[4, 1],
3411///         &[4, 2],
3412///         &[4, 3],
3413///         &[1, 2, 3],
3414///         &[1, 2, 4],
3415///         &[1, 3, 2],
3416///         &[1, 3, 4],
3417///         &[1, 4, 2],
3418///         &[1, 4, 3],
3419///         &[2, 1, 3],
3420///         &[2, 1, 4]
3421///     ]
3422/// );
3423/// ```
3424#[inline]
3425pub fn shortlex_unique_vecs_min_length<I: Clone + Iterator>(
3426    min_length: u64,
3427    xs: I,
3428) -> ShortlexUniqueVecs<I>
3429where
3430    I::Item: Clone,
3431{
3432    shortlex_unique_vecs_length_inclusive_range(min_length, u64::MAX, xs)
3433}
3434
3435/// Generates [`Vec`]s, with lengths in a range $[a, b)$, with elements from a single iterator, such
3436/// that each [`Vec`] has no repeated elements.
3437///
3438/// The [`Vec`]s are generated in order of increasing length, and within each length they are
3439/// ordered lexicographically with respect to the order of the element iterator.
3440///
3441/// The source iterator should not repeat any elements, but this is not enforced.
3442///
3443/// The iterator should be finite; if it is infinite, [`Vec`]s of length `\max(2, a + 1)` and above
3444/// will never be generated.
3445///
3446/// If $a \leq b$, the output is empty.
3447///
3448/// If $a = 0$ and $b = 1$, the output consists of a single empty [`Vec`].
3449///
3450/// If the input iterator is infinite and $0 < a < b$, the output length is also infinite.
3451///
3452/// If the input iterator length is $n$, the output length is
3453/// $$
3454/// \sum_{i=a}^{b - 1} \frac{n!}{k!}.
3455/// $$
3456///
3457/// # Examples
3458/// ```
3459/// use itertools::Itertools;
3460/// use malachite_base::vecs::exhaustive::shortlex_unique_vecs_length_range;
3461///
3462/// let xss = shortlex_unique_vecs_length_range(2, 4, 1..=4)
3463///     .take(20)
3464///     .collect_vec();
3465/// assert_eq!(
3466///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
3467///     &[
3468///         &[1, 2][..],
3469///         &[1, 3],
3470///         &[1, 4],
3471///         &[2, 1],
3472///         &[2, 3],
3473///         &[2, 4],
3474///         &[3, 1],
3475///         &[3, 2],
3476///         &[3, 4],
3477///         &[4, 1],
3478///         &[4, 2],
3479///         &[4, 3],
3480///         &[1, 2, 3],
3481///         &[1, 2, 4],
3482///         &[1, 3, 2],
3483///         &[1, 3, 4],
3484///         &[1, 4, 2],
3485///         &[1, 4, 3],
3486///         &[2, 1, 3],
3487///         &[2, 1, 4]
3488///     ]
3489/// );
3490/// ```
3491#[inline]
3492pub fn shortlex_unique_vecs_length_range<I: Clone + Iterator>(
3493    mut a: u64,
3494    mut b: u64,
3495    xs: I,
3496) -> ShortlexUniqueVecs<I>
3497where
3498    I::Item: Clone,
3499{
3500    if b == 0 {
3501        // Transform an empty (x, 0) range into (2, 1), which is also empty but doesn't cause
3502        // overflow
3503        a = 2;
3504        b = 1;
3505    }
3506    shortlex_unique_vecs_length_inclusive_range(a, b - 1, xs)
3507}
3508
3509/// Generates [`Vec`]s, with lengths in a range $[a, b]$, with elements from a single iterator, such
3510/// that each [`Vec`] has no repeated elements.
3511///
3512/// The [`Vec`]s are generated in order of increasing length, and within each length they are
3513/// ordered lexicographically with respect to the order of the element iterator.
3514///
3515/// The source iterator should not repeat any elements, but this is not enforced.
3516///
3517/// The iterator should be finite; if it is infinite, [`Vec`]s of length `\max(2, a + 1)` and above
3518/// will never be generated.
3519///
3520/// If $a < b$, the output is empty.
3521///
3522/// If $a = b = 0$, the output consists of a single empty [`Vec`].
3523///
3524/// If the input iterator is infinite and $0 < a \leq b$, the output length is also infinite.
3525///
3526/// If the input iterator length is $n$, the output length is
3527/// $$
3528/// \sum_{i=a}^b \frac{n!}{k!}.
3529/// $$
3530///
3531/// # Examples
3532/// ```
3533/// use itertools::Itertools;
3534/// use malachite_base::vecs::exhaustive::shortlex_unique_vecs_length_inclusive_range;
3535///
3536/// let xss = shortlex_unique_vecs_length_inclusive_range(2, 3, 1..=4)
3537///     .take(20)
3538///     .collect_vec();
3539/// assert_eq!(
3540///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
3541///     &[
3542///         &[1, 2][..],
3543///         &[1, 3],
3544///         &[1, 4],
3545///         &[2, 1],
3546///         &[2, 3],
3547///         &[2, 4],
3548///         &[3, 1],
3549///         &[3, 2],
3550///         &[3, 4],
3551///         &[4, 1],
3552///         &[4, 2],
3553///         &[4, 3],
3554///         &[1, 2, 3],
3555///         &[1, 2, 4],
3556///         &[1, 3, 2],
3557///         &[1, 3, 4],
3558///         &[1, 4, 2],
3559///         &[1, 4, 3],
3560///         &[2, 1, 3],
3561///         &[2, 1, 4]
3562///     ]
3563/// );
3564/// ```
3565#[inline]
3566pub fn shortlex_unique_vecs_length_inclusive_range<I: Clone + Iterator>(
3567    a: u64,
3568    b: u64,
3569    xs: I,
3570) -> ShortlexUniqueVecs<I>
3571where
3572    I::Item: Clone,
3573{
3574    ShortlexUniqueVecs::new(a, b, xs)
3575}
3576
3577fn compare_indexed_vecs_lex<T>(xs: &[(usize, T)], ys: &[(usize, T)]) -> Ordering {
3578    let xs_len = xs.len();
3579    let ys_len = ys.len();
3580    for i in 0..min(xs_len, ys_len) {
3581        let o = xs[i].0.cmp(&ys[i].0);
3582        if o != Equal {
3583            return o;
3584        }
3585    }
3586    xs_len.cmp(&ys_len)
3587}
3588
3589/// Generates all collections of elements from an iterator in lexicographic order, where the
3590/// collections have no repetitions.
3591#[derive(Clone)]
3592pub struct LexUniqueVecs<I: Clone + Iterator>
3593where
3594    I::Item: Clone,
3595{
3596    done: bool,
3597    first: bool,
3598    min: usize,
3599    max: usize,
3600    xs_for_prefix: I,
3601    xs: I,
3602    phase_1_vec: Option<Vec<I::Item>>,
3603    xsss: Vec<LexUniqueVecsFixedLength<Zip<RangeFrom<usize>, I>>>,
3604    next_xss: Vec<Option<Vec<(usize, I::Item)>>>,
3605}
3606
3607impl<I: Clone + Iterator> Iterator for LexUniqueVecs<I>
3608where
3609    I::Item: Clone,
3610{
3611    type Item = Vec<I::Item>;
3612
3613    fn next(&mut self) -> Option<Vec<I::Item>> {
3614        if self.done {
3615            return None;
3616        }
3617        if self.first {
3618            self.first = false;
3619            return self.phase_1_vec.clone();
3620        }
3621        if let Some(prefix) = self.phase_1_vec.as_mut() {
3622            if prefix.len() < self.max {
3623                if let Some(x) = self.xs_for_prefix.next() {
3624                    prefix.push(x);
3625                    return Some(prefix.clone());
3626                }
3627                self.max = prefix.len();
3628            }
3629        }
3630        if self.phase_1_vec.is_some() {
3631            for k in self.min..=self.max {
3632                let mut xss =
3633                    lex_unique_vecs_fixed_length(u64::exact_from(k), (0..).zip(self.xs.clone()));
3634                // Skip over first Vec of length k, which was already generated in phase 1
3635                xss.next();
3636                self.next_xss.push(xss.next());
3637                self.xsss.push(xss);
3638            }
3639            self.phase_1_vec = None;
3640        }
3641        let mut min_i = None;
3642        let mut i_done = None;
3643        for i in 0..self.next_xss.len() {
3644            let choose = if let Some(xs) = &self.next_xss[i] {
3645                if let Some(min_i) = min_i {
3646                    let ys: &Option<Vec<(usize, I::Item)>> = &self.next_xss[min_i];
3647                    compare_indexed_vecs_lex(xs, ys.as_ref().unwrap()) == Less
3648                } else {
3649                    true
3650                }
3651            } else {
3652                i_done = Some(i);
3653                false
3654            };
3655            if choose {
3656                min_i = Some(i);
3657            }
3658        }
3659        if let Some(i) = min_i {
3660            self.next_xss.push(self.xsss[i].next());
3661            let xs = self
3662                .next_xss
3663                .swap_remove(i)
3664                .map(|xs| xs.into_iter().map(|p| p.1).collect());
3665            if let Some(i_done) = i_done {
3666                self.xsss.remove(i_done);
3667                self.next_xss.remove(i_done);
3668            }
3669            xs
3670        } else {
3671            self.done = true;
3672            None
3673        }
3674    }
3675}
3676
3677/// Generates [`Vec`]s with elements from a single iterator, such that each [`Vec`] has no repeated
3678/// elements.
3679///
3680/// The [`Vec`]s are ordered lexicographically with respect to the order of the element iterator.
3681///
3682/// The source iterator should not repeat any elements, but this is not enforced.
3683///
3684/// The iterator should be finite; if it is infinite, only prefixes of the iterator will be
3685/// generated.
3686///
3687/// If the input iterator is infinite, the output length is also infinite.
3688///
3689/// If the input iterator length is $n$, the output length is
3690/// $$
3691/// \sum_ {k=0}^n \frac{n!}{k!}
3692/// $$
3693/// $$
3694/// = \\begin{cases}
3695///     1 & \text{if} \\quad n = 0, \\\\
3696///     2 & \text{if} \\quad n = 1, \\\\
3697///     \operatorname{round}(en!) & \\text{otherwise}.
3698/// \\end{cases}
3699/// $$
3700///
3701/// See <https://oeis.org/A000522>.
3702///
3703/// If `xs` is empty, the output consists of a single empty [`Vec`].
3704///
3705/// # Examples
3706/// ```
3707/// use itertools::Itertools;
3708/// use malachite_base::vecs::exhaustive::lex_unique_vecs;
3709///
3710/// let xss = lex_unique_vecs(1..=4).take(20).collect_vec();
3711/// assert_eq!(
3712///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
3713///     &[
3714///         &[][..],
3715///         &[1],
3716///         &[1, 2],
3717///         &[1, 2, 3],
3718///         &[1, 2, 3, 4],
3719///         &[1, 2, 4],
3720///         &[1, 2, 4, 3],
3721///         &[1, 3],
3722///         &[1, 3, 2],
3723///         &[1, 3, 2, 4],
3724///         &[1, 3, 4],
3725///         &[1, 3, 4, 2],
3726///         &[1, 4],
3727///         &[1, 4, 2],
3728///         &[1, 4, 2, 3],
3729///         &[1, 4, 3],
3730///         &[1, 4, 3, 2],
3731///         &[2],
3732///         &[2, 1],
3733///         &[2, 1, 3]
3734///     ]
3735/// );
3736/// ```
3737#[inline]
3738pub fn lex_unique_vecs<I: Clone + Iterator>(xs: I) -> LexUniqueVecs<I>
3739where
3740    I::Item: Clone,
3741{
3742    lex_unique_vecs_length_inclusive_range(0, u64::MAX, xs)
3743}
3744
3745/// Generates [`Vec`]s with a mininum length, with elements from a single iterator, such that each
3746/// [`Vec`] has no repeated elements.
3747///
3748/// The [`Vec`]s are ordered lexicographically with respect to the order of the element iterator.
3749///
3750/// The source iterator should not repeat any elements, but this is not enforced.
3751///
3752/// The iterator should be finite; if it is infinite, only prefixes of the iterator will be
3753/// generated.
3754///
3755/// If the input iterator is infinite, the output length is also infinite.
3756///
3757/// If the input iterator length is $n$ and the `min_length` is $\ell$, the output length is
3758/// $$
3759/// \sum_{i=\ell}^n \frac{n!}{k!}.
3760/// $$
3761///
3762/// # Examples
3763/// ```
3764/// use itertools::Itertools;
3765/// use malachite_base::vecs::exhaustive::lex_unique_vecs_min_length;
3766///
3767/// let xss = lex_unique_vecs_min_length(2, 1..=4).take(20).collect_vec();
3768/// assert_eq!(
3769///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
3770///     &[
3771///         &[1, 2][..],
3772///         &[1, 2, 3],
3773///         &[1, 2, 3, 4],
3774///         &[1, 2, 4],
3775///         &[1, 2, 4, 3],
3776///         &[1, 3],
3777///         &[1, 3, 2],
3778///         &[1, 3, 2, 4],
3779///         &[1, 3, 4],
3780///         &[1, 3, 4, 2],
3781///         &[1, 4],
3782///         &[1, 4, 2],
3783///         &[1, 4, 2, 3],
3784///         &[1, 4, 3],
3785///         &[1, 4, 3, 2],
3786///         &[2, 1],
3787///         &[2, 1, 3],
3788///         &[2, 1, 3, 4],
3789///         &[2, 1, 4],
3790///         &[2, 1, 4, 3]
3791///     ]
3792/// );
3793/// ```
3794#[inline]
3795pub fn lex_unique_vecs_min_length<I: Clone + Iterator>(min_length: u64, xs: I) -> LexUniqueVecs<I>
3796where
3797    I::Item: Clone,
3798{
3799    lex_unique_vecs_length_inclusive_range(min_length, u64::MAX, xs)
3800}
3801
3802/// Generates [`Vec`]s, with lengths in a range $[a, b)$, with elements from a single iterator, such
3803/// that each [`Vec`] has no repeated elements.
3804///
3805/// The [`Vec`]s are ordered lexicographically with respect to the order of the element iterator.
3806///
3807/// The source iterator should not repeat any elements, but this is not enforced.
3808///
3809/// The iterator should be finite; if it is infinite, only prefixes of the iterator will be
3810/// generated.
3811///
3812/// If $a \leq b$, the output is empty.
3813///
3814/// If $a = 0$ and $b = 1$, the output consists of a single empty [`Vec`].
3815///
3816/// If the input iterator is infinite and $0 < a < b$, the output length is also infinite.
3817///
3818/// If the input iterator length is $n$, the output length is
3819/// $$
3820/// \sum_{i=a}^{b - 1} \frac{n!}{k!}.
3821/// $$
3822///
3823/// # Examples
3824/// ```
3825/// use itertools::Itertools;
3826/// use malachite_base::vecs::exhaustive::lex_unique_vecs_length_range;
3827///
3828/// let xss = lex_unique_vecs_length_range(2, 4, 1..=4)
3829///     .take(20)
3830///     .collect_vec();
3831/// assert_eq!(
3832///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
3833///     &[
3834///         &[1, 2][..],
3835///         &[1, 2, 3],
3836///         &[1, 2, 4],
3837///         &[1, 3],
3838///         &[1, 3, 2],
3839///         &[1, 3, 4],
3840///         &[1, 4],
3841///         &[1, 4, 2],
3842///         &[1, 4, 3],
3843///         &[2, 1],
3844///         &[2, 1, 3],
3845///         &[2, 1, 4],
3846///         &[2, 3],
3847///         &[2, 3, 1],
3848///         &[2, 3, 4],
3849///         &[2, 4],
3850///         &[2, 4, 1],
3851///         &[2, 4, 3],
3852///         &[3, 1],
3853///         &[3, 1, 2]
3854///     ]
3855/// );
3856/// ```
3857#[inline]
3858pub fn lex_unique_vecs_length_range<I: Clone + Iterator>(
3859    mut a: u64,
3860    mut b: u64,
3861    xs: I,
3862) -> LexUniqueVecs<I>
3863where
3864    I::Item: Clone,
3865{
3866    if b == 0 {
3867        // Transform an empty (x, 0) range into (2, 1), which is also empty but doesn't cause
3868        // overflow
3869        a = 2;
3870        b = 1;
3871    }
3872    lex_unique_vecs_length_inclusive_range(a, b - 1, xs)
3873}
3874
3875/// Generates [`Vec`]s with a mininum length, with elements from a single iterator, such that each
3876/// [`Vec`] has no repeated elements.
3877///
3878/// The [`Vec`]s are ordered lexicographically with respect to the order of the element iterator.
3879///
3880/// The source iterator should not repeat any elements, but this is not enforced.
3881///
3882/// The iterator should be finite; if it is infinite, only prefixes of the iterator will be
3883/// generated.
3884///
3885/// If the input iterator is infinite, the output length is also infinite.
3886///
3887/// If the input iterator length is $n$ and the `min_length` is $\ell$, the output length is
3888/// $$
3889/// \sum_{i=\ell}^n \frac{n!}{k!}.
3890/// $$
3891///
3892/// # Examples
3893/// ```
3894/// use itertools::Itertools;
3895/// use malachite_base::vecs::exhaustive::lex_unique_vecs_min_length;
3896///
3897/// let xss = lex_unique_vecs_min_length(2, 1..=4).take(20).collect_vec();
3898/// assert_eq!(
3899///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
3900///     &[
3901///         &[1, 2][..],
3902///         &[1, 2, 3],
3903///         &[1, 2, 3, 4],
3904///         &[1, 2, 4],
3905///         &[1, 2, 4, 3],
3906///         &[1, 3],
3907///         &[1, 3, 2],
3908///         &[1, 3, 2, 4],
3909///         &[1, 3, 4],
3910///         &[1, 3, 4, 2],
3911///         &[1, 4],
3912///         &[1, 4, 2],
3913///         &[1, 4, 2, 3],
3914///         &[1, 4, 3],
3915///         &[1, 4, 3, 2],
3916///         &[2, 1],
3917///         &[2, 1, 3],
3918///         &[2, 1, 3, 4],
3919///         &[2, 1, 4],
3920///         &[2, 1, 4, 3]
3921///     ]
3922/// );
3923/// ```
3924#[inline]
3925pub fn lex_unique_vecs_length_inclusive_range<I: Clone + Iterator>(
3926    a: u64,
3927    b: u64,
3928    xs: I,
3929) -> LexUniqueVecs<I>
3930where
3931    I::Item: Clone,
3932{
3933    let a = usize::exact_from(a);
3934    let b = usize::exact_from(b);
3935    let mut xs_for_prefix = xs.clone();
3936    let phase_1_vec = (&mut xs_for_prefix).take(a).collect_vec();
3937    LexUniqueVecs {
3938        done: a > b || phase_1_vec.len() < a,
3939        first: true,
3940        min: a,
3941        max: b,
3942        xs_for_prefix,
3943        xs,
3944        phase_1_vec: Some(phase_1_vec),
3945        xsss: Vec::new(),
3946        next_xss: Vec::new(),
3947    }
3948}
3949
3950#[doc(hidden)]
3951#[derive(Clone)]
3952pub struct ExhaustiveUniqueVecs2<I: Iterator>
3953where
3954    I::Item: Clone,
3955{
3956    next: Option<(I::Item, I::Item)>,
3957    ps: ExhaustiveOrderedUniqueCollections<I, Vec<I::Item>>,
3958}
3959
3960impl<I: Iterator> Iterator for ExhaustiveUniqueVecs2<I>
3961where
3962    I::Item: Clone,
3963{
3964    type Item = Vec<I::Item>;
3965
3966    fn next(&mut self) -> Option<Vec<I::Item>> {
3967        if self.next.is_some() {
3968            let (a, b) = take(&mut self.next).unwrap();
3969            Some(vec![a, b])
3970        } else if let Some(p) = self.ps.next() {
3971            self.next = Some((p[1].clone(), p[0].clone()));
3972            Some(p)
3973        } else {
3974            None
3975        }
3976    }
3977}
3978
3979fn exhaustive_unique_vecs_2<I: Iterator>(xs: I) -> ExhaustiveUniqueVecs2<I>
3980where
3981    I::Item: Clone,
3982{
3983    ExhaustiveUniqueVecs2 {
3984        next: None,
3985        ps: exhaustive_ordered_unique_vecs_fixed_length(2, xs),
3986    }
3987}
3988
3989#[doc(hidden)]
3990#[derive(Clone, Debug)]
3991pub struct ExhaustiveUniqueVecsGenerator<T: Clone, I: Iterator<Item = T>> {
3992    phantom_t: PhantomData<T>,
3993    phantom_i: PhantomData<I>,
3994}
3995
3996impl<T: Clone, I: Iterator<Item = T>> ExhaustiveUniqueVecsGenerator<T, I> {
3997    #[doc(hidden)]
3998    #[inline]
3999    pub const fn new() -> ExhaustiveUniqueVecsGenerator<T, I> {
4000        ExhaustiveUniqueVecsGenerator {
4001            phantom_i: PhantomData,
4002            phantom_t: PhantomData,
4003        }
4004    }
4005}
4006
4007impl<T: Clone, I: Iterator<Item = T>>
4008    ExhaustiveDependentPairsYsGenerator<Vec<T>, Vec<T>, ExhaustiveVecPermutations<T>>
4009    for ExhaustiveUniqueVecsGenerator<T, I>
4010{
4011    #[inline]
4012    fn get_ys(&self, xs: &Vec<T>) -> ExhaustiveVecPermutations<T> {
4013        exhaustive_vec_permutations(xs.clone())
4014    }
4015}
4016
4017/// Generates all fixed-length [`Vec`]s of elements from an iterator, where the [`Vec`]s have no
4018/// repetitions and are ordered the same way as in the iterator.
4019#[derive(Clone)]
4020pub enum ExhaustiveUniqueVecsFixedLength<I: Iterator>
4021where
4022    I::Item: Clone,
4023{
4024    Zero(bool),
4025    One(I),
4026    Two(ExhaustiveUniqueVecs2<I>),
4027    GreaterThanTwo(
4028        ExhaustiveDependentPairs<
4029            Vec<I::Item>,
4030            Vec<I::Item>,
4031            RulerSequence<usize>,
4032            ExhaustiveUniqueVecsGenerator<I::Item, I>,
4033            ExhaustiveOrderedUniqueCollections<I, Vec<I::Item>>,
4034            ExhaustiveVecPermutations<I::Item>,
4035        >,
4036    ),
4037}
4038
4039impl<I: Iterator> Iterator for ExhaustiveUniqueVecsFixedLength<I>
4040where
4041    I::Item: Clone,
4042{
4043    type Item = Vec<I::Item>;
4044
4045    fn next(&mut self) -> Option<Vec<I::Item>> {
4046        match self {
4047            ExhaustiveUniqueVecsFixedLength::Zero(done) => {
4048                if *done {
4049                    None
4050                } else {
4051                    *done = true;
4052                    Some(Vec::new())
4053                }
4054            }
4055            ExhaustiveUniqueVecsFixedLength::One(xs) => xs.next().map(|x| vec![x]),
4056            ExhaustiveUniqueVecsFixedLength::Two(ps) => ps.next(),
4057            ExhaustiveUniqueVecsFixedLength::GreaterThanTwo(xss) => xss.next().map(|p| p.1),
4058        }
4059    }
4060}
4061
4062/// Generates [`Vec`]s of a given length with elements from a single iterator, such that each
4063/// [`Vec`] has no repeated elements.
4064///
4065/// The source iterator should not repeat any elements, but this is not enforced.
4066///
4067/// If $k$ is 0, the output length is 1.
4068///
4069/// If $k$ is nonzero and the input iterator is infinite, the output length is also infinite.
4070///
4071/// If $k$ is nonzero and the input iterator length is $n$, the output length is
4072/// $$
4073/// (n)_ k = \prod_ {i=0}^{k-1}(n - i) = frac{n!}{(n-k)!}.
4074/// $$
4075///
4076/// If $k$ is 0, the output consists of one empty [`Vec`].
4077///
4078/// If `xs` is empty, the output is also empty, unless $k$ is 0.
4079///
4080/// # Examples
4081/// ```
4082/// use itertools::Itertools;
4083/// use malachite_base::vecs::exhaustive::exhaustive_unique_vecs_fixed_length;
4084///
4085/// let xss = exhaustive_unique_vecs_fixed_length(4, 1..=6)
4086///     .take(20)
4087///     .collect_vec();
4088/// assert_eq!(
4089///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
4090///     &[
4091///         &[1, 2, 3, 4],
4092///         &[1, 2, 3, 5],
4093///         &[1, 2, 4, 3],
4094///         &[1, 2, 4, 5],
4095///         &[1, 3, 2, 4],
4096///         &[1, 2, 5, 3],
4097///         &[1, 3, 4, 2],
4098///         &[1, 3, 4, 5],
4099///         &[1, 4, 2, 3],
4100///         &[1, 3, 2, 5],
4101///         &[1, 4, 3, 2],
4102///         &[1, 2, 5, 4],
4103///         &[2, 1, 3, 4],
4104///         &[1, 3, 5, 2],
4105///         &[2, 1, 4, 3],
4106///         &[2, 3, 4, 5],
4107///         &[2, 3, 1, 4],
4108///         &[1, 5, 2, 3],
4109///         &[2, 3, 4, 1],
4110///         &[1, 4, 2, 5]
4111///     ]
4112/// );
4113/// ```
4114pub fn exhaustive_unique_vecs_fixed_length<I: Iterator>(
4115    k: u64,
4116    xs: I,
4117) -> ExhaustiveUniqueVecsFixedLength<I>
4118where
4119    I::Item: Clone,
4120{
4121    match k {
4122        0 => ExhaustiveUniqueVecsFixedLength::Zero(false),
4123        1 => ExhaustiveUniqueVecsFixedLength::One(xs),
4124        2 => ExhaustiveUniqueVecsFixedLength::Two(exhaustive_unique_vecs_2(xs)),
4125        k => ExhaustiveUniqueVecsFixedLength::GreaterThanTwo(exhaustive_dependent_pairs(
4126            ruler_sequence(),
4127            exhaustive_ordered_unique_vecs_fixed_length(k, xs),
4128            ExhaustiveUniqueVecsGenerator::new(),
4129        )),
4130    }
4131}
4132
4133/// Generates all [`Vec`]s of elements from an iterator, where the [`Vec`]s have no repetitions and
4134/// are ordered the same way as in the iterator.
4135#[derive(Clone)]
4136pub struct ExhaustiveUniqueVecs<I: Iterator>
4137where
4138    I::Item: Clone,
4139{
4140    xs: ExhaustiveDependentPairs<
4141        Vec<I::Item>,
4142        Vec<I::Item>,
4143        RulerSequence<usize>,
4144        ExhaustiveUniqueVecsGenerator<I::Item, I>,
4145        ExhaustiveOrderedUniqueCollections<I, Vec<I::Item>>,
4146        ExhaustiveVecPermutations<I::Item>,
4147    >,
4148}
4149
4150impl<I: Iterator> Iterator for ExhaustiveUniqueVecs<I>
4151where
4152    I::Item: Clone,
4153{
4154    type Item = Vec<I::Item>;
4155
4156    #[inline]
4157    fn next(&mut self) -> Option<Vec<I::Item>> {
4158        self.xs.next().map(|p| p.1)
4159    }
4160}
4161
4162/// Generates [`Vec`]s with elements from a single iterator, such that each [`Vec`] has no repeated
4163/// elements.
4164///
4165/// The source iterator should not repeat any elements, but this is not enforced.
4166///
4167/// If the input iterator is infinite, the output length is also infinite.
4168///
4169/// If the input iterator length is $n$, the output length is
4170/// $$
4171/// \sum_ {k=0}^n \frac{n!}{k!}
4172/// $$
4173/// $$
4174/// = \\begin{cases}
4175///     1 & \text{if} \\quad n = 0, \\\\
4176///     2 & \text{if} \\quad n = 1, \\\\
4177///     \operatorname{round}(en!) & \\text{otherwise}.
4178/// \\end{cases}
4179/// $$
4180///
4181/// See <https://oeis.org/A000522>.
4182///
4183/// If `xs` is empty, the output consists of a single empty [`Vec`].
4184///
4185/// # Examples
4186/// ```
4187/// use itertools::Itertools;
4188/// use malachite_base::vecs::exhaustive::exhaustive_unique_vecs;
4189///
4190/// let xss = exhaustive_unique_vecs(1..=4).take(20).collect_vec();
4191/// assert_eq!(
4192///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
4193///     &[
4194///         &[][..],
4195///         &[1],
4196///         &[2],
4197///         &[3],
4198///         &[1, 2],
4199///         &[1, 3],
4200///         &[2, 1],
4201///         &[1, 2, 3],
4202///         &[3, 1],
4203///         &[2, 3],
4204///         &[3, 2],
4205///         &[4],
4206///         &[1, 3, 2],
4207///         &[1, 4],
4208///         &[2, 1, 3],
4209///         &[3, 4],
4210///         &[2, 3, 1],
4211///         &[4, 1],
4212///         &[3, 1, 2],
4213///         &[2, 4]
4214///     ]
4215/// );
4216/// ```
4217#[inline]
4218pub fn exhaustive_unique_vecs<I: Iterator>(xs: I) -> ExhaustiveUniqueVecs<I>
4219where
4220    I::Item: Clone,
4221{
4222    ExhaustiveUniqueVecs {
4223        xs: exhaustive_dependent_pairs(
4224            ruler_sequence(),
4225            exhaustive_ordered_unique_vecs(xs),
4226            ExhaustiveUniqueVecsGenerator::new(),
4227        ),
4228    }
4229}
4230
4231/// Generates [`Vec`]s with a mininum length, with elements from a single iterator, such that each
4232/// [`Vec`] has no repeated elements.
4233///
4234/// The source iterator should not repeat any elements, but this is not enforced.
4235///
4236/// If the input iterator is infinite, the output length is also infinite.
4237///
4238/// If the input iterator length is $n$ and the `min_length` is $\ell$, the output length is
4239/// $$
4240/// \sum_ {k=\ell}^n \frac{n!}{k!}.
4241/// $$
4242///
4243/// # Examples
4244/// ```
4245/// use itertools::Itertools;
4246/// use malachite_base::vecs::exhaustive::exhaustive_unique_vecs_min_length;
4247///
4248/// let xss = exhaustive_unique_vecs_min_length(2, 1..=4)
4249///     .take(20)
4250///     .collect_vec();
4251/// assert_eq!(
4252///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
4253///     &[
4254///         &[1, 2][..],
4255///         &[1, 3],
4256///         &[2, 1],
4257///         &[2, 3],
4258///         &[3, 1],
4259///         &[3, 2],
4260///         &[1, 2, 3],
4261///         &[1, 2, 4],
4262///         &[1, 3, 2],
4263///         &[1, 4],
4264///         &[2, 1, 3],
4265///         &[2, 4],
4266///         &[2, 3, 1],
4267///         &[4, 1],
4268///         &[3, 1, 2],
4269///         &[3, 4],
4270///         &[3, 2, 1],
4271///         &[4, 2],
4272///         &[1, 4, 2],
4273///         &[1, 3, 4]
4274///     ]
4275/// );
4276/// ```
4277#[inline]
4278pub fn exhaustive_unique_vecs_min_length<I: Iterator>(
4279    min_length: u64,
4280    xs: I,
4281) -> ExhaustiveUniqueVecs<I>
4282where
4283    I::Item: Clone,
4284{
4285    ExhaustiveUniqueVecs {
4286        xs: exhaustive_dependent_pairs(
4287            ruler_sequence(),
4288            exhaustive_ordered_unique_vecs_min_length(min_length, xs),
4289            ExhaustiveUniqueVecsGenerator::new(),
4290        ),
4291    }
4292}
4293
4294/// Generates [`Vec`]s, with lengths in a range $[a, b)$, with elements from a single iterator, such
4295/// that each [`Vec`] has no repeated elements.
4296///
4297/// The source iterator should not repeat any elements, but this is not enforced.
4298///
4299/// If $a \leq b$, the output is empty.
4300///
4301/// If $a = 0$ and $b = 1$, the output consists of a single empty [`Vec`].
4302///
4303/// If the input iterator is infinite and $0 < a < b$, the output length is also infinite.
4304///
4305/// If the input iterator length is $n$, the output length is
4306/// $$
4307/// \sum_{i=a}^{b - 1} \frac{n!}{k!}.
4308/// $$
4309///
4310/// # Examples
4311/// ```
4312/// use itertools::Itertools;
4313/// use malachite_base::vecs::exhaustive::exhaustive_unique_vecs_length_range;
4314///
4315/// let xss = exhaustive_unique_vecs_length_range(2, 4, 1..=4)
4316///     .take(20)
4317///     .collect_vec();
4318/// assert_eq!(
4319///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
4320///     &[
4321///         &[1, 2][..],
4322///         &[1, 3],
4323///         &[2, 1],
4324///         &[2, 3],
4325///         &[3, 1],
4326///         &[3, 2],
4327///         &[1, 2, 3],
4328///         &[1, 2, 4],
4329///         &[1, 3, 2],
4330///         &[1, 4],
4331///         &[2, 1, 3],
4332///         &[2, 4],
4333///         &[2, 3, 1],
4334///         &[4, 1],
4335///         &[3, 1, 2],
4336///         &[3, 4],
4337///         &[3, 2, 1],
4338///         &[4, 2],
4339///         &[1, 4, 2],
4340///         &[1, 3, 4]
4341///     ]
4342/// );
4343/// ```
4344#[inline]
4345pub fn exhaustive_unique_vecs_length_range<I: Iterator>(
4346    a: u64,
4347    b: u64,
4348    xs: I,
4349) -> ExhaustiveUniqueVecs<I>
4350where
4351    I::Item: Clone,
4352{
4353    ExhaustiveUniqueVecs {
4354        xs: exhaustive_dependent_pairs(
4355            ruler_sequence(),
4356            exhaustive_ordered_unique_vecs_length_range(a, b, xs),
4357            ExhaustiveUniqueVecsGenerator::new(),
4358        ),
4359    }
4360}
4361
4362/// Generates [`Vec`]s, with lengths in a range $[a, b]$, with elements from a single iterator, such
4363/// that each [`Vec`] has no repeated elements.
4364///
4365/// The source iterator should not repeat any elements, but this is not enforced.
4366///
4367/// If $a < b$, the output is empty.
4368///
4369/// If $a = b = 0$, the output consists of a single empty [`Vec`].
4370///
4371/// If the input iterator is infinite and $0 < a \leq b$, the output length is also infinite.
4372///
4373/// If the input iterator length is $n$, the output length is
4374/// $$
4375/// \sum_{i=a}^b \frac{n!}{k!}.
4376/// $$
4377///
4378/// # Examples
4379/// ```
4380/// use itertools::Itertools;
4381/// use malachite_base::vecs::exhaustive::exhaustive_unique_vecs_length_inclusive_range;
4382///
4383/// let xss = exhaustive_unique_vecs_length_inclusive_range(2, 3, 1..=4)
4384///     .take(20)
4385///     .collect_vec();
4386/// assert_eq!(
4387///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
4388///     &[
4389///         &[1, 2][..],
4390///         &[1, 3],
4391///         &[2, 1],
4392///         &[2, 3],
4393///         &[3, 1],
4394///         &[3, 2],
4395///         &[1, 2, 3],
4396///         &[1, 2, 4],
4397///         &[1, 3, 2],
4398///         &[1, 4],
4399///         &[2, 1, 3],
4400///         &[2, 4],
4401///         &[2, 3, 1],
4402///         &[4, 1],
4403///         &[3, 1, 2],
4404///         &[3, 4],
4405///         &[3, 2, 1],
4406///         &[4, 2],
4407///         &[1, 4, 2],
4408///         &[1, 3, 4]
4409///     ]
4410/// );
4411/// ```
4412#[inline]
4413pub fn exhaustive_unique_vecs_length_inclusive_range<I: Iterator>(
4414    a: u64,
4415    b: u64,
4416    xs: I,
4417) -> ExhaustiveUniqueVecs<I>
4418where
4419    I::Item: Clone,
4420{
4421    ExhaustiveUniqueVecs {
4422        xs: exhaustive_dependent_pairs(
4423            ruler_sequence(),
4424            exhaustive_ordered_unique_vecs_length_inclusive_range(a, b, xs),
4425            ExhaustiveUniqueVecsGenerator::new(),
4426        ),
4427    }
4428}
4429
4430/// Generates all $k$-compositions of a number: all length-$k$ [`Vec`]s of positive [`usize`]s whose
4431/// sum is a given number.
4432#[derive(Clone, Debug)]
4433pub struct LexKCompositions {
4434    done: bool,
4435    first: bool,
4436    xs: Vec<usize>,
4437}
4438
4439impl Iterator for LexKCompositions {
4440    type Item = Vec<usize>;
4441
4442    fn next(&mut self) -> Option<Vec<usize>> {
4443        if self.done {
4444            return None;
4445        } else if self.first {
4446            self.first = false;
4447            return Some(self.xs.clone());
4448        }
4449        let last_not_one_index = self.xs.iter().rposition(|&x| x != 1);
4450        if last_not_one_index.is_none() || last_not_one_index == Some(0) {
4451            self.done = true;
4452            return None;
4453        }
4454        let last_not_one_index = last_not_one_index.unwrap();
4455        self.xs[last_not_one_index - 1] += 1;
4456        let last_not_one = self.xs[last_not_one_index];
4457        let (last, init) = self.xs.split_last_mut().unwrap();
4458        *last = last_not_one - 1;
4459        for x in &mut init[last_not_one_index..] {
4460            *x = 1;
4461        }
4462        Some(self.xs.clone())
4463    }
4464}
4465
4466/// Generates all $k$-compositions of a number: given $n$ and $k$, generates all length-$k$ [`Vec`]s
4467/// of positive [`usize`]s whose sum is $n$.
4468///
4469/// The [`Vec`]s are output in lexicographic order.
4470///
4471/// If $k = 0$ and $n \neq 0$, or if $n < k$, then the output is empty.
4472///
4473/// The output length is
4474/// $$
4475/// \binom{n-1}{k-1}.
4476/// $$
4477///
4478/// # Examples
4479/// ```
4480/// use itertools::Itertools;
4481/// use malachite_base::vecs::exhaustive::lex_k_compositions;
4482///
4483/// let xss = lex_k_compositions(5, 3).collect_vec();
4484/// assert_eq!(
4485///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
4486///     &[&[1, 1, 3], &[1, 2, 2], &[1, 3, 1], &[2, 1, 2], &[2, 2, 1], &[3, 1, 1]]
4487/// );
4488/// ```
4489pub fn lex_k_compositions(n: usize, k: usize) -> LexKCompositions {
4490    if k == 0 && n != 0 || n < k {
4491        return LexKCompositions {
4492            done: true,
4493            first: true,
4494            xs: Vec::new(),
4495        };
4496    }
4497    let mut xs = vec![1; k];
4498    if k != 0 {
4499        xs[k - 1] = n + 1 - k;
4500    }
4501    LexKCompositions {
4502        done: false,
4503        first: true,
4504        xs,
4505    }
4506}
4507
4508#[doc(hidden)]
4509#[derive(Clone, Debug)]
4510pub struct LexKCompositionsGenerator {
4511    k: usize,
4512}
4513
4514impl ExhaustiveDependentPairsYsGenerator<usize, Vec<usize>, LexKCompositions>
4515    for LexKCompositionsGenerator
4516{
4517    #[inline]
4518    fn get_ys(&self, &n: &usize) -> LexKCompositions {
4519        lex_k_compositions(n, self.k)
4520    }
4521}
4522
4523/// Generates $k$-compositions of $n$ for all $n$ in a given range: all length-$k$ [`Vec`]s of
4524/// positive [`usize`]s whose sum is in a given range.
4525#[derive(Clone, Debug)]
4526pub struct ExhaustiveCombinedKCompositions {
4527    xs: ExhaustiveDependentPairs<
4528        usize,
4529        Vec<usize>,
4530        RulerSequence<usize>,
4531        LexKCompositionsGenerator,
4532        PrimitiveIntIncreasingRange<usize>,
4533        LexKCompositions,
4534    >,
4535}
4536
4537impl Iterator for ExhaustiveCombinedKCompositions {
4538    type Item = Vec<usize>;
4539
4540    #[inline]
4541    fn next(&mut self) -> Option<Vec<usize>> {
4542        self.xs.next().map(|p| p.1)
4543    }
4544}
4545
4546/// Given $n_\text{min}$, $n_\text{max}$, and $k$, generates all length-$k$ [`Vec`]s of positive
4547/// [`usize`]s whose sum is in the closed interval $[n_\text{min}, n_\text{max}]$.
4548///
4549/// The output length is
4550/// $$
4551/// \sum_{n=n_\text{min}}^{n_\text{max}} \binom{n-1}{k-1}.
4552/// $$
4553///
4554/// # Panics
4555/// Panics if $n_\text{min} > n_\text{max}$.
4556///
4557/// # Examples
4558/// ```
4559/// use itertools::Itertools;
4560/// use malachite_base::vecs::exhaustive::exhaustive_combined_k_compositions;
4561///
4562/// let xss = exhaustive_combined_k_compositions(4, 6, 3).collect_vec();
4563/// assert_eq!(
4564///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
4565///     &[
4566///         &[1, 1, 2],
4567///         &[1, 1, 3],
4568///         &[1, 2, 1],
4569///         &[1, 1, 4],
4570///         &[2, 1, 1],
4571///         &[1, 2, 2],
4572///         &[1, 3, 1],
4573///         &[1, 2, 3],
4574///         &[2, 1, 2],
4575///         &[1, 3, 2],
4576///         &[2, 2, 1],
4577///         &[3, 1, 1],
4578///         &[1, 4, 1],
4579///         &[2, 1, 3],
4580///         &[2, 2, 2],
4581///         &[2, 3, 1],
4582///         &[3, 1, 2],
4583///         &[3, 2, 1],
4584///         &[4, 1, 1]
4585///     ]
4586/// );
4587/// ```
4588#[inline]
4589pub fn exhaustive_combined_k_compositions(
4590    n_min: usize,
4591    n_max: usize,
4592    k: usize,
4593) -> ExhaustiveCombinedKCompositions {
4594    ExhaustiveCombinedKCompositions {
4595        xs: exhaustive_dependent_pairs(
4596            ruler_sequence(),
4597            primitive_int_increasing_inclusive_range(n_min, n_max),
4598            LexKCompositionsGenerator { k },
4599        ),
4600    }
4601}