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 Self::Zero(xs) => xs.next(),
432 Self::One(xs) => xs.next().map(|x| vec![x]),
433 Self::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 Self::Zero(xs) => xs.next(),
902 Self::One(xs) => xs.next().map(|x| vec![x]),
903 Self::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: PhantomData<(I::Item, C)>,
1772}
1773
1774impl<I: Iterator, C: FromIterator<I::Item>> LexFixedLengthOrderedUniqueCollections<I, C>
1775where
1776 I::Item: Clone,
1777{
1778 pub fn new(k: u64, xs: I) -> Self {
1779 Self {
1780 first: true,
1781 done: false,
1782 xs: IteratorCache::new(xs),
1783 indices: (0..usize::exact_from(k)).collect(),
1784 phantom: PhantomData,
1785 }
1786 }
1787}
1788
1789#[doc(hidden)]
1790pub fn fixed_length_ordered_unique_indices_helper(
1791 n: usize,
1792 k: usize,
1793 indices: &mut [usize],
1794) -> bool {
1795 let mut expected_j = n - 1;
1796 let mut i = k - 1;
1797 // Find longest suffix of the form [..., n - 3, n - 2, n - 1]. After this loop, i is the index
1798 // right before this longest suffix.
1799 loop {
1800 if expected_j != indices[i] {
1801 break;
1802 }
1803 if i == 0 {
1804 return true;
1805 }
1806 i -= 1;
1807 expected_j -= 1;
1808 }
1809 let mut j = indices[i] + 1;
1810 for index in &mut indices[i..] {
1811 *index = j;
1812 j += 1;
1813 }
1814 false
1815}
1816
1817impl<I: Iterator, C: FromIterator<I::Item>> Iterator
1818 for LexFixedLengthOrderedUniqueCollections<I, C>
1819where
1820 I::Item: Clone,
1821{
1822 type Item = C;
1823
1824 fn next(&mut self) -> Option<C> {
1825 if self.done {
1826 return None;
1827 }
1828 let k = self.indices.len();
1829 if self.first {
1830 self.first = false;
1831 self.xs.get(k);
1832 if let Some(n) = self.xs.known_len()
1833 && n < k
1834 {
1835 self.done = true;
1836 return None;
1837 }
1838 } else {
1839 if k == 0 {
1840 self.done = true;
1841 return None;
1842 }
1843 if let Some(n) = self.xs.known_len() {
1844 if fixed_length_ordered_unique_indices_helper(n, k, &mut self.indices) {
1845 self.done = true;
1846 return None;
1847 }
1848 } else {
1849 *self.indices.last_mut().unwrap() += 1;
1850 }
1851 }
1852 if let Some(&last_index) = self.indices.last() {
1853 // Give known len a chance to be set
1854 self.xs.get(last_index + 1);
1855 }
1856 Some(
1857 self.indices
1858 .iter()
1859 .map(|&i| self.xs.assert_get(i).clone())
1860 .collect(),
1861 )
1862 }
1863}
1864
1865/// Generates [`Vec`]s of a given length with elements from a single iterator, such that each
1866/// [`Vec`] has no repeated elements, and the elements in each [`Vec`] are ordered the same way as
1867/// they are in the source iterator.
1868///
1869/// The source iterator should not repeat any elements, but this is not enforced.
1870///
1871/// The order is lexicographic with respect to the order of the element iterator.
1872///
1873/// If $k$ is 0, the output length is 1.
1874///
1875/// If $k$ is nonzero and the input iterator is infinite, the output length is also infinite.
1876///
1877/// If $k$ is nonzero and the input iterator length is $n$, the output length is $\binom{n}{k}$.
1878///
1879/// If $k$ is 0, the output consists of one empty [`Vec`].
1880///
1881/// If `xs` is empty, the output is also empty, unless $k$ is 0.
1882///
1883/// # Examples
1884/// ```
1885/// use itertools::Itertools;
1886/// use malachite_base::vecs::exhaustive::lex_ordered_unique_vecs_fixed_length;
1887///
1888/// let xss = lex_ordered_unique_vecs_fixed_length(4, 1..=6).collect_vec();
1889/// assert_eq!(
1890/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
1891/// &[
1892/// &[1, 2, 3, 4],
1893/// &[1, 2, 3, 5],
1894/// &[1, 2, 3, 6],
1895/// &[1, 2, 4, 5],
1896/// &[1, 2, 4, 6],
1897/// &[1, 2, 5, 6],
1898/// &[1, 3, 4, 5],
1899/// &[1, 3, 4, 6],
1900/// &[1, 3, 5, 6],
1901/// &[1, 4, 5, 6],
1902/// &[2, 3, 4, 5],
1903/// &[2, 3, 4, 6],
1904/// &[2, 3, 5, 6],
1905/// &[2, 4, 5, 6],
1906/// &[3, 4, 5, 6]
1907/// ]
1908/// );
1909/// ```
1910#[inline]
1911pub fn lex_ordered_unique_vecs_fixed_length<I: Iterator>(
1912 k: u64,
1913 xs: I,
1914) -> LexFixedLengthOrderedUniqueCollections<I, Vec<I::Item>>
1915where
1916 I::Item: Clone,
1917{
1918 LexFixedLengthOrderedUniqueCollections::new(k, xs)
1919}
1920
1921/// Generates all collections of elements from an iterator in shortlex order, where the collections
1922/// have no repetitions and are ordered the same way as in the iterator.
1923#[derive(Clone)]
1924pub struct ShortlexOrderedUniqueCollections<I: Clone + Iterator, C: FromIterator<I::Item>>
1925where
1926 I::Item: Clone,
1927{
1928 current_len: u64,
1929 max_len: u64,
1930 xs: I,
1931 current_xss: LexFixedLengthOrderedUniqueCollections<I, C>,
1932}
1933
1934impl<I: Clone + Iterator, C: FromIterator<I::Item>> ShortlexOrderedUniqueCollections<I, C>
1935where
1936 I::Item: Clone,
1937{
1938 pub(crate) fn new(a: u64, b: u64, xs: I) -> Self {
1939 Self {
1940 current_len: a,
1941 max_len: b,
1942 xs: xs.clone(),
1943 current_xss: LexFixedLengthOrderedUniqueCollections::new(a, xs),
1944 }
1945 }
1946}
1947
1948impl<I: Clone + Iterator, C: FromIterator<I::Item>> Iterator
1949 for ShortlexOrderedUniqueCollections<I, C>
1950where
1951 I::Item: Clone,
1952{
1953 type Item = C;
1954
1955 fn next(&mut self) -> Option<C> {
1956 if self.current_len > self.max_len {
1957 return None;
1958 }
1959 if let Some(next) = self.current_xss.next() {
1960 Some(next)
1961 } else {
1962 self.current_len += 1;
1963 if self.current_len > self.max_len {
1964 return None;
1965 }
1966 self.current_xss = LexFixedLengthOrderedUniqueCollections {
1967 first: true,
1968 done: false,
1969 xs: IteratorCache::new(self.xs.clone()),
1970 indices: (0..usize::exact_from(self.current_len)).collect(),
1971 phantom: PhantomData,
1972 };
1973 if let Some(next) = self.current_xss.next() {
1974 Some(next)
1975 } else {
1976 // Prevent any further iteration
1977 self.max_len = 0;
1978 self.current_len = 1;
1979 None
1980 }
1981 }
1982 }
1983}
1984
1985/// Generates [`Vec`]s with elements from a single iterator, such that each [`Vec`] has no repeated
1986/// elements, and the elements in each [`Vec`] are ordered the same way as they are in the source
1987/// iterator.
1988///
1989/// The [`Vec`]s are generated in order of increasing length, and within each length they are
1990/// ordered lexicographically with respect to the order of the element iterator.
1991///
1992/// The source iterator should not repeat any elements, but this is not enforced.
1993///
1994/// The iterator should be finite; if it is infinite, [`Vec`]s of length 2 and above will never be
1995/// generated.
1996///
1997/// If the input iterator is infinite, the output length is also infinite.
1998///
1999/// If the input iterator length is $n$, the output length is $2^n$.
2000///
2001/// If `xs` is empty, the output consists of a single empty [`Vec`].
2002///
2003/// # Examples
2004/// ```
2005/// use itertools::Itertools;
2006/// use malachite_base::vecs::exhaustive::shortlex_ordered_unique_vecs;
2007///
2008/// let xss = shortlex_ordered_unique_vecs(1..=4).collect_vec();
2009/// assert_eq!(
2010/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2011/// &[
2012/// &[][..],
2013/// &[1],
2014/// &[2],
2015/// &[3],
2016/// &[4],
2017/// &[1, 2],
2018/// &[1, 3],
2019/// &[1, 4],
2020/// &[2, 3],
2021/// &[2, 4],
2022/// &[3, 4],
2023/// &[1, 2, 3],
2024/// &[1, 2, 4],
2025/// &[1, 3, 4],
2026/// &[2, 3, 4],
2027/// &[1, 2, 3, 4]
2028/// ]
2029/// );
2030/// ```
2031#[inline]
2032pub fn shortlex_ordered_unique_vecs<I: Clone + Iterator>(
2033 xs: I,
2034) -> ShortlexOrderedUniqueCollections<I, Vec<I::Item>>
2035where
2036 I::Item: Clone,
2037{
2038 shortlex_ordered_unique_vecs_length_inclusive_range(0, u64::MAX, xs)
2039}
2040
2041/// Generates [`Vec`]s with a mininum length, with elements from a single iterator, such that each
2042/// [`Vec`] has no repeated elements, and the elements in each [`Vec`] are ordered the same way as
2043/// they are in the source iterator.
2044///
2045/// The [`Vec`]s are generated in order of increasing length, and within each length they are
2046/// ordered lexicographically with respect to the order of the element iterator.
2047///
2048/// The source iterator should not repeat any elements, but this is not enforced.
2049///
2050/// The iterator should be finite; if it is infinite, [`Vec`]s of length `\max(2, \ell + 1)` and
2051/// above will never be generated.
2052///
2053/// If the input iterator is infinite, the output length is also infinite.
2054///
2055/// If the input iterator length is $n$ and the `min_length` is $\ell$, the output length is
2056/// $$
2057/// \sum_{i=\ell}^n \binom{n}{i}.
2058/// $$
2059///
2060/// # Examples
2061/// ```
2062/// use itertools::Itertools;
2063/// use malachite_base::vecs::exhaustive::shortlex_ordered_unique_vecs_min_length;
2064///
2065/// let xss = shortlex_ordered_unique_vecs_min_length(2, 1..=4).collect_vec();
2066/// assert_eq!(
2067/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2068/// &[
2069/// &[1, 2][..],
2070/// &[1, 3],
2071/// &[1, 4],
2072/// &[2, 3],
2073/// &[2, 4],
2074/// &[3, 4],
2075/// &[1, 2, 3],
2076/// &[1, 2, 4],
2077/// &[1, 3, 4],
2078/// &[2, 3, 4],
2079/// &[1, 2, 3, 4]
2080/// ]
2081/// );
2082/// ```
2083#[inline]
2084pub fn shortlex_ordered_unique_vecs_min_length<I: Clone + Iterator>(
2085 min_length: u64,
2086 xs: I,
2087) -> ShortlexOrderedUniqueCollections<I, Vec<I::Item>>
2088where
2089 I::Item: Clone,
2090{
2091 shortlex_ordered_unique_vecs_length_inclusive_range(min_length, u64::MAX, xs)
2092}
2093
2094/// Generates [`Vec`]s, with lengths in a range $[a, b)$, with elements from a single iterator, such
2095/// that each [`Vec`] has no repeated elements, and the elements in each [`Vec`] are ordered the
2096/// same way as they are in the source iterator.
2097///
2098/// The [`Vec`]s are generated in order of increasing length, and within each length they are
2099/// ordered lexicographically with respect to the order of the element iterator.
2100///
2101/// The source iterator should not repeat any elements, but this is not enforced.
2102///
2103/// The iterator should be finite; if it is infinite, [`Vec`]s of length `\max(2, a + 1)` and above
2104/// will never be generated.
2105///
2106/// If $a \leq b$, the output is empty.
2107///
2108/// If $a = 0$ and $b = 1$, the output consists of a single empty [`Vec`].
2109///
2110/// If the input iterator is infinite and $0 < a < b$, the output length is also infinite.
2111///
2112/// If the input iterator length is $n$, the output length is
2113/// $$
2114/// \sum_{i=a}^{b - 1} \binom{n}{i}.
2115/// $$
2116///
2117/// # Examples
2118/// ```
2119/// use itertools::Itertools;
2120/// use malachite_base::vecs::exhaustive::shortlex_ordered_unique_vecs_length_range;
2121///
2122/// let xss = shortlex_ordered_unique_vecs_length_range(2, 4, 1..=4).collect_vec();
2123/// assert_eq!(
2124/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2125/// &[
2126/// &[1, 2][..],
2127/// &[1, 3],
2128/// &[1, 4],
2129/// &[2, 3],
2130/// &[2, 4],
2131/// &[3, 4],
2132/// &[1, 2, 3],
2133/// &[1, 2, 4],
2134/// &[1, 3, 4],
2135/// &[2, 3, 4],
2136/// ]
2137/// );
2138/// ```
2139#[inline]
2140pub fn shortlex_ordered_unique_vecs_length_range<I: Clone + Iterator>(
2141 mut a: u64,
2142 mut b: u64,
2143 xs: I,
2144) -> ShortlexOrderedUniqueCollections<I, Vec<I::Item>>
2145where
2146 I::Item: Clone,
2147{
2148 if b == 0 {
2149 // Transform an empty (x, 0) range into (2, 1), which is also empty but doesn't cause
2150 // overflow
2151 a = 2;
2152 b = 1;
2153 }
2154 shortlex_ordered_unique_vecs_length_inclusive_range(a, b - 1, xs)
2155}
2156
2157/// Generates [`Vec`]s, with lengths in a range $[a, b]$, with elements from a single iterator, such
2158/// that each [`Vec`] has no repeated elements, and the elements in each [`Vec`] are ordered the
2159/// same way as they are in the source iterator.
2160///
2161/// The [`Vec`]s are generated in order of increasing length, and within each length they are
2162/// ordered lexicographically with respect to the order of the element iterator.
2163///
2164/// The source iterator should not repeat any elements, but this is not enforced.
2165///
2166/// The iterator should be finite; if it is infinite, [`Vec`]s of length `\max(2, a + 1)` and above
2167/// will never be generated.
2168///
2169/// If $a < b$, the output is empty.
2170///
2171/// If $a = b = 0$, the output consists of a single empty [`Vec`].
2172///
2173/// If the input iterator is infinite and $0 < a \leq b$, the output length is also infinite.
2174///
2175/// If the input iterator length is $n$, the output length is
2176/// $$
2177/// \sum_{i=a}^b \binom{n}{i}.
2178/// $$
2179///
2180/// # Examples
2181/// ```
2182/// use itertools::Itertools;
2183/// use malachite_base::vecs::exhaustive::shortlex_ordered_unique_vecs_length_inclusive_range;
2184///
2185/// let xss = shortlex_ordered_unique_vecs_length_inclusive_range(2, 3, 1..=4).collect_vec();
2186/// assert_eq!(
2187/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2188/// &[
2189/// &[1, 2][..],
2190/// &[1, 3],
2191/// &[1, 4],
2192/// &[2, 3],
2193/// &[2, 4],
2194/// &[3, 4],
2195/// &[1, 2, 3],
2196/// &[1, 2, 4],
2197/// &[1, 3, 4],
2198/// &[2, 3, 4],
2199/// ]
2200/// );
2201/// ```
2202#[inline]
2203pub fn shortlex_ordered_unique_vecs_length_inclusive_range<I: Clone + Iterator>(
2204 a: u64,
2205 b: u64,
2206 xs: I,
2207) -> ShortlexOrderedUniqueCollections<I, Vec<I::Item>>
2208where
2209 I::Item: Clone,
2210{
2211 ShortlexOrderedUniqueCollections::new(a, b, xs)
2212}
2213
2214/// Generates all collections of elements from an iterator in lexicographic order, where the
2215/// collections have no repetitions and are ordered the same way as in the iterator.
2216#[derive(Clone, Debug)]
2217pub struct LexOrderedUniqueCollections<I: Iterator, C: FromIterator<I::Item>>
2218where
2219 I::Item: Clone,
2220{
2221 done: bool,
2222 first: bool,
2223 min_len: usize,
2224 max_len: usize,
2225 xs: IteratorCache<I>,
2226 indices: Vec<usize>,
2227 phantom: PhantomData<(I::Item, C)>,
2228}
2229
2230impl<I: Iterator, C: FromIterator<I::Item>> LexOrderedUniqueCollections<I, C>
2231where
2232 I::Item: Clone,
2233{
2234 pub(crate) fn new(a: u64, b: u64, xs: I) -> Self {
2235 Self {
2236 done: a > b,
2237 first: true,
2238 min_len: usize::exact_from(a),
2239 max_len: usize::exact_from(b),
2240 xs: IteratorCache::new(xs),
2241 indices: (0..usize::exact_from(a)).collect(),
2242 phantom: PhantomData,
2243 }
2244 }
2245}
2246
2247impl<I: Iterator, C: FromIterator<I::Item>> Iterator for LexOrderedUniqueCollections<I, C>
2248where
2249 I::Item: Clone,
2250{
2251 type Item = C;
2252
2253 fn next(&mut self) -> Option<C> {
2254 if self.done {
2255 return None;
2256 }
2257 let k = self.indices.len();
2258 if self.first {
2259 self.first = false;
2260 self.xs.get(k);
2261 if let Some(n) = self.xs.known_len()
2262 && n < k
2263 {
2264 self.done = true;
2265 return None;
2266 }
2267 } else if k == 0 {
2268 if self.xs.get(0).is_none() {
2269 self.done = true;
2270 return None;
2271 }
2272 self.indices.push(0);
2273 } else {
2274 let last_i = *self.indices.last().unwrap();
2275 let next_i = last_i + 1;
2276 if k < self.max_len && self.xs.get(next_i).is_some() {
2277 // For example, if xs is [0, 1, 2, 3] and max_len is 4, then the next set of indices
2278 // after [0, 1] is [0, 1, 2].
2279 self.indices.push(next_i);
2280 } else if k == self.min_len {
2281 // For example, if xs is [0, 1, 2, 3] and min_len is 2, then the next set of indices
2282 // after [1, 3] is [2, 3].
2283 if let Some(n) = self.xs.known_len() {
2284 if fixed_length_ordered_unique_indices_helper(n, k, &mut self.indices) {
2285 self.done = true;
2286 return None;
2287 }
2288 } else {
2289 *self.indices.last_mut().unwrap() += 1;
2290 }
2291 } else if self.xs.get(next_i).is_some() {
2292 // For example, if xs is [0, 1, 2, 3] and max_len is 3, then the next set of indices
2293 // after [1, 2, 3] is [1, 2, 4].
2294 *self.indices.last_mut().unwrap() = next_i;
2295 } else {
2296 let x = self.indices.pop();
2297 if let Some(last) = self.indices.last_mut() {
2298 // For example, if xs is [0, 1, 2, 3] and max_len is 3, then the next set of
2299 // indices after [0, 1, 2] is [0, 1, 3].
2300 *last += 1;
2301 } else {
2302 let next_x = x.unwrap() + 1;
2303 if self.xs.get(next_x).is_none() {
2304 // For example, if xs is [0, 1, 2, 3], then nothing comes after the indices
2305 // [3].
2306 self.done = true;
2307 return None;
2308 }
2309 // For example, if xs is [0, 1, 2, 3] and max_len is 1, then the next set of
2310 // indices after [0] is [1].
2311 self.indices.push(next_x);
2312 }
2313 }
2314 }
2315 if let Some(&last_index) = self.indices.last() {
2316 // Give known len a chance to be set
2317 self.xs.get(last_index + 1);
2318 }
2319 Some(
2320 self.indices
2321 .iter()
2322 .map(|&i| self.xs.assert_get(i).clone())
2323 .collect(),
2324 )
2325 }
2326}
2327
2328/// Generates [`Vec`]s with elements from a single iterator, such that each [`Vec`] has no repeated
2329/// elements, and the elements in each [`Vec`] are ordered the same way as they are in the source
2330/// iterator.
2331///
2332/// The [`Vec`]s are ordered lexicographically with respect to the order of the element iterator.
2333///
2334/// The source iterator should not repeat any elements, but this is not enforced.
2335///
2336/// The iterator should be finite; if it is infinite, only prefixes of the iterator will be
2337/// generated.
2338///
2339/// If the input iterator is infinite, the output length is also infinite.
2340///
2341/// If the input iterator length is $n$, the output length is $2^n$.
2342///
2343/// If `xs` is empty, the output consists of a single empty [`Vec`].
2344///
2345/// # Examples
2346/// ```
2347/// use itertools::Itertools;
2348/// use malachite_base::vecs::exhaustive::lex_ordered_unique_vecs;
2349///
2350/// let xss = lex_ordered_unique_vecs(1..=4).collect_vec();
2351/// assert_eq!(
2352/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2353/// &[
2354/// &[][..],
2355/// &[1],
2356/// &[1, 2],
2357/// &[1, 2, 3],
2358/// &[1, 2, 3, 4],
2359/// &[1, 2, 4],
2360/// &[1, 3],
2361/// &[1, 3, 4],
2362/// &[1, 4],
2363/// &[2],
2364/// &[2, 3],
2365/// &[2, 3, 4],
2366/// &[2, 4],
2367/// &[3],
2368/// &[3, 4],
2369/// &[4]
2370/// ]
2371/// );
2372/// ```
2373#[inline]
2374pub fn lex_ordered_unique_vecs<I: Clone + Iterator>(
2375 xs: I,
2376) -> LexOrderedUniqueCollections<I, Vec<I::Item>>
2377where
2378 I::Item: Clone,
2379{
2380 lex_ordered_unique_vecs_length_inclusive_range(0, u64::MAX, xs)
2381}
2382
2383/// Generates [`Vec`]s with a mininum length, with elements from a single iterator, such that each
2384/// [`Vec`] has no repeated elements, and the elements in each [`Vec`] are ordered the same way as
2385/// they are in the source iterator.
2386///
2387/// The [`Vec`]s are ordered lexicographically with respect to the order of the element iterator.
2388///
2389/// The source iterator should not repeat any elements, but this is not enforced.
2390///
2391/// The iterator should be finite; if it is infinite, only prefixes of the iterator will be
2392/// generated.
2393///
2394/// If the input iterator is infinite, the output length is also infinite.
2395///
2396/// If the input iterator length is $n$ and the `min_length` is $\ell$, the output length is
2397/// $$
2398/// \sum_{i=\ell}^n \binom{n}{i}.
2399/// $$
2400///
2401/// # Examples
2402/// ```
2403/// use itertools::Itertools;
2404/// use malachite_base::vecs::exhaustive::lex_ordered_unique_vecs_min_length;
2405///
2406/// let xss = lex_ordered_unique_vecs_min_length(2, 1..=4).collect_vec();
2407/// assert_eq!(
2408/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2409/// &[
2410/// &[1, 2][..],
2411/// &[1, 2, 3],
2412/// &[1, 2, 3, 4],
2413/// &[1, 2, 4],
2414/// &[1, 3],
2415/// &[1, 3, 4],
2416/// &[1, 4],
2417/// &[2, 3],
2418/// &[2, 3, 4],
2419/// &[2, 4],
2420/// &[3, 4],
2421/// ]
2422/// );
2423/// ```
2424#[inline]
2425pub fn lex_ordered_unique_vecs_min_length<I: Clone + Iterator>(
2426 min_length: u64,
2427 xs: I,
2428) -> LexOrderedUniqueCollections<I, Vec<I::Item>>
2429where
2430 I::Item: Clone,
2431{
2432 lex_ordered_unique_vecs_length_inclusive_range(min_length, u64::MAX, xs)
2433}
2434
2435/// Generates [`Vec`]s, with lengths in a range $[a, b)$, with elements from a single iterator, such
2436/// that each [`Vec`] has no repeated elements, and the elements in each [`Vec`] are ordered the
2437/// same way as they are in the source iterator.
2438///
2439/// The [`Vec`]s are ordered lexicographically with respect to the order of the element iterator.
2440///
2441/// The source iterator should not repeat any elements, but this is not enforced.
2442///
2443/// The iterator should be finite; if it is infinite, only prefixes of the iterator will be
2444/// generated.
2445///
2446/// If $a \leq b$, the output is empty.
2447///
2448/// If $a = 0$ and $b = 1$, the output consists of a single empty [`Vec`].
2449///
2450/// If the input iterator is infinite and $0 < a < b$, the output length is also infinite.
2451///
2452/// If the input iterator length is $n$, the output length is
2453/// $$
2454/// \sum_{i=a}^{b - 1} \binom{n}{i}.
2455/// $$
2456///
2457/// # Examples
2458/// ```
2459/// use itertools::Itertools;
2460/// use malachite_base::vecs::exhaustive::lex_ordered_unique_vecs_length_range;
2461///
2462/// let xss = lex_ordered_unique_vecs_length_range(2, 4, 1..=4).collect_vec();
2463/// assert_eq!(
2464/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2465/// &[
2466/// &[1, 2][..],
2467/// &[1, 2, 3],
2468/// &[1, 2, 4],
2469/// &[1, 3],
2470/// &[1, 3, 4],
2471/// &[1, 4],
2472/// &[2, 3],
2473/// &[2, 3, 4],
2474/// &[2, 4],
2475/// &[3, 4],
2476/// ]
2477/// );
2478/// ```
2479#[inline]
2480pub fn lex_ordered_unique_vecs_length_range<I: Clone + Iterator>(
2481 mut a: u64,
2482 mut b: u64,
2483 xs: I,
2484) -> LexOrderedUniqueCollections<I, Vec<I::Item>>
2485where
2486 I::Item: Clone,
2487{
2488 if b == 0 {
2489 // Transform an empty (x, 0) range into (2, 1), which is also empty but doesn't cause
2490 // overflow
2491 a = 2;
2492 b = 1;
2493 }
2494 lex_ordered_unique_vecs_length_inclusive_range(a, b - 1, xs)
2495}
2496
2497/// Generates [`Vec`]s, with lengths in a range $[a, b]$, with elements from a single iterator, such
2498/// that each [`Vec`] has no repeated elements, and the elements in each [`Vec`] are ordered the
2499/// same way as they are in the source iterator.
2500///
2501/// The [`Vec`]s are ordered lexicographically with respect to the order of the element iterator.
2502///
2503/// The source iterator should not repeat any elements, but this is not enforced.
2504///
2505/// The iterator should be finite; if it is infinite, only prefixes of the iterator will be
2506/// generated.
2507///
2508/// If $a < b$, the output is empty.
2509///
2510/// If $a = b = 0$, the output consists of a single empty [`Vec`].
2511///
2512/// If the input iterator is infinite and $0 < a \leq b$, the output length is also infinite.
2513///
2514/// If the input iterator length is $n$, the output length is
2515/// $$
2516/// \sum_{i=a}^b \binom{n}{i}.
2517/// $$
2518///
2519/// # Examples
2520/// ```
2521/// use itertools::Itertools;
2522/// use malachite_base::vecs::exhaustive::lex_ordered_unique_vecs_length_inclusive_range;
2523///
2524/// let xss = lex_ordered_unique_vecs_length_inclusive_range(2, 3, 1..=4).collect_vec();
2525/// assert_eq!(
2526/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2527/// &[
2528/// &[1, 2][..],
2529/// &[1, 2, 3],
2530/// &[1, 2, 4],
2531/// &[1, 3],
2532/// &[1, 3, 4],
2533/// &[1, 4],
2534/// &[2, 3],
2535/// &[2, 3, 4],
2536/// &[2, 4],
2537/// &[3, 4],
2538/// ]
2539/// );
2540/// ```
2541#[inline]
2542pub fn lex_ordered_unique_vecs_length_inclusive_range<I: Clone + Iterator>(
2543 a: u64,
2544 b: u64,
2545 xs: I,
2546) -> LexOrderedUniqueCollections<I, Vec<I::Item>>
2547where
2548 I::Item: Clone,
2549{
2550 LexOrderedUniqueCollections::new(a, b, xs)
2551}
2552
2553/// This function is used for iterating through all bit patterns with a specified number of minimum
2554/// and maximum `true` bits.
2555///
2556/// Given an existing bit pattern, and a reference `bit_count`, which must equal the number of
2557/// `true`s in the pattern, mutates the pattern into the next pattern with a valid number of `true`
2558/// bits. See the unit tests for many examples.
2559///
2560/// # Worst-case complexity
2561/// $$
2562/// T(k) = O(k)
2563/// $$
2564///
2565/// $$
2566/// M(k) = O(k)
2567/// $$
2568///
2569/// where $T$ is time, $M$ is additional memory, and $k$ is the length of `pattern`. The memory
2570/// usage is only linear when the pattern vector needs to be reallocated, which happens rarely.
2571///
2572/// # Panics
2573/// Panics if `max_bits` is zero. (However, `min_bits` may be zero.)
2574///
2575/// # Examples
2576/// ```
2577/// use malachite_base::vecs::exhaustive::next_bit_pattern;
2578///
2579/// // Suppose we are generating all bit patterns with 2 to 4 true bits, inclusive. Suppose our
2580/// // current pattern is `1111000`. Then, the lexicographically next largest valid pattern is
2581/// // `10000001`. (All patterns of the form `1111xxx`, where the `x`s are not all zero, have too
2582/// // many ones. That brings us to `10000000`, which has too few ones, and then `10000001`.)
2583/// //
2584/// // The patterns are represented "in reverse", with least-significant bits appearing first.
2585/// let mut pattern = vec![false, false, false, true, true, true, true];
2586/// let mut bit_count = 4;
2587/// next_bit_pattern(&mut pattern, &mut bit_count, 2, 4);
2588/// assert_eq!(
2589/// pattern,
2590/// &[true, false, false, false, false, false, false, true]
2591/// );
2592/// assert_eq!(bit_count, 2);
2593/// ```
2594pub fn next_bit_pattern(
2595 pattern: &mut Vec<bool>,
2596 bit_count: &mut usize,
2597 min_bits: usize,
2598 max_bits: usize,
2599) {
2600 assert_ne!(max_bits, 0);
2601 match pattern.first() {
2602 None => {
2603 pattern.push(true);
2604 *bit_count = 1;
2605 }
2606 Some(&false) => {
2607 if *bit_count < max_bits {
2608 pattern[0] = true;
2609 *bit_count += 1;
2610 } else {
2611 let leading_false_count = pattern.iter().take_while(|&&b| !b).count();
2612 let true_after_false_count = pattern[leading_false_count..]
2613 .iter()
2614 .take_while(|&&b| b)
2615 .count();
2616 let tf_count = leading_false_count + true_after_false_count;
2617 if tf_count == pattern.len() {
2618 for b in &mut *pattern {
2619 *b = false;
2620 }
2621 pattern.push(true);
2622 *bit_count = 1;
2623 } else {
2624 for b in &mut pattern[leading_false_count..tf_count] {
2625 *b = false;
2626 }
2627 pattern[tf_count] = true;
2628 *bit_count -= true_after_false_count - 1;
2629 }
2630 if *bit_count < min_bits {
2631 let diff = min_bits - *bit_count;
2632 for b in &mut pattern[..diff] {
2633 *b = true;
2634 }
2635 *bit_count += diff;
2636 }
2637 }
2638 }
2639 Some(&true) => {
2640 let leading_true_count = pattern.iter().take_while(|&&b| b).count();
2641 for b in &mut pattern[..leading_true_count] {
2642 *b = false;
2643 }
2644 if leading_true_count == pattern.len() {
2645 pattern.push(true);
2646 } else {
2647 pattern[leading_true_count] = true;
2648 }
2649 *bit_count -= leading_true_count - 1;
2650 if *bit_count < min_bits {
2651 let diff = min_bits - *bit_count;
2652 for b in &mut pattern[..diff] {
2653 *b = true;
2654 }
2655 *bit_count += diff;
2656 }
2657 }
2658 }
2659}
2660
2661#[derive(Clone)]
2662#[doc(hidden)]
2663pub struct ExhaustiveOrderedUniqueCollectionsGreaterThanOne<I: Iterator, C: FromIterator<I::Item>>
2664where
2665 I::Item: Clone,
2666{
2667 done: bool,
2668 first: bool,
2669 min_bits: usize,
2670 max_bits: usize,
2671 xs: IteratorCache<I>,
2672 pattern: Vec<bool>,
2673 bit_count: usize,
2674 phantom: PhantomData<*const C>,
2675}
2676
2677impl<I: Iterator, C: FromIterator<I::Item>> Iterator
2678 for ExhaustiveOrderedUniqueCollectionsGreaterThanOne<I, C>
2679where
2680 I::Item: Clone,
2681{
2682 type Item = C;
2683
2684 fn next(&mut self) -> Option<C> {
2685 if self.done {
2686 return None;
2687 } else if self.first {
2688 self.first = false;
2689 } else {
2690 next_bit_pattern(
2691 &mut self.pattern,
2692 &mut self.bit_count,
2693 self.min_bits,
2694 self.max_bits,
2695 );
2696 }
2697 if !self.pattern.is_empty() && self.xs.get(self.pattern.len() - 1).is_none() {
2698 self.done = true;
2699 return None;
2700 }
2701 Some(
2702 self.pattern
2703 .iter()
2704 .enumerate()
2705 .filter_map(|(i, &b)| {
2706 if b {
2707 Some(self.xs.assert_get(i).clone())
2708 } else {
2709 None
2710 }
2711 })
2712 .collect(),
2713 )
2714 }
2715}
2716
2717/// Generates all collections of elements from an iterator, where the collections have no
2718/// repetitions and are ordered the same way as in the iterator.
2719#[derive(Clone)]
2720pub enum ExhaustiveOrderedUniqueCollections<I: Iterator, C: FromIterator<I::Item>>
2721where
2722 I::Item: Clone,
2723{
2724 None,
2725 Zero(bool),
2726 ZeroOne(bool, I),
2727 One(I),
2728 GreaterThanOne(ExhaustiveOrderedUniqueCollectionsGreaterThanOne<I, C>),
2729}
2730
2731impl<I: Iterator, C: FromIterator<I::Item>> ExhaustiveOrderedUniqueCollections<I, C>
2732where
2733 I::Item: Clone,
2734{
2735 pub(crate) fn new(a: u64, b: u64, xs: I) -> Self {
2736 match (a, b) {
2737 (a, b) if a > b => Self::None,
2738 (0, 0) => Self::Zero(false),
2739 (0, 1) => Self::ZeroOne(true, xs),
2740 (1, 1) => Self::One(xs),
2741 (a, b) => Self::GreaterThanOne(ExhaustiveOrderedUniqueCollectionsGreaterThanOne {
2742 done: false,
2743 first: true,
2744 min_bits: usize::saturating_from(a),
2745 max_bits: usize::saturating_from(b),
2746 xs: IteratorCache::new(xs),
2747 pattern: vec![true; usize::saturating_from(a)],
2748 bit_count: usize::saturating_from(a),
2749 phantom: PhantomData,
2750 }),
2751 }
2752 }
2753}
2754
2755impl<I: Iterator, C: FromIterator<I::Item>> Iterator for ExhaustiveOrderedUniqueCollections<I, C>
2756where
2757 I::Item: Clone,
2758{
2759 type Item = C;
2760
2761 fn next(&mut self) -> Option<C> {
2762 match self {
2763 Self::None => None,
2764 Self::Zero(done) => {
2765 if *done {
2766 None
2767 } else {
2768 *done = true;
2769 Some(empty().collect())
2770 }
2771 }
2772 Self::ZeroOne(first, xs) => {
2773 if *first {
2774 *first = false;
2775 Some(empty().collect())
2776 } else {
2777 xs.next().map(|x| once(x).collect())
2778 }
2779 }
2780 Self::One(xs) => xs.next().map(|x| once(x).collect()),
2781 Self::GreaterThanOne(xs) => xs.next(),
2782 }
2783 }
2784}
2785
2786/// Generates [`Vec`]s of a given length with elements from a single iterator, such that each
2787/// [`Vec`] has no repeated elements, and the elements in each [`Vec`] are ordered the same way as
2788/// they are in the source iterator.
2789///
2790/// The source iterator should not repeat any elements, but this is not enforced.
2791///
2792/// If $k$ is 0, the output length is 1.
2793///
2794/// If $k$ is nonzero and the input iterator is infinite, the output length is also infinite.
2795///
2796/// If $k$ is nonzero and the input iterator length is $n$, the output length is $\binom{n}{k}$.
2797///
2798/// If $k$ is 0, the output consists of one empty [`Vec`].
2799///
2800/// If `xs` is empty, the output is also empty, unless $k$ is 0.
2801///
2802/// # Examples
2803/// ```
2804/// use itertools::Itertools;
2805/// use malachite_base::vecs::exhaustive::exhaustive_ordered_unique_vecs_fixed_length;
2806///
2807/// let xss = exhaustive_ordered_unique_vecs_fixed_length(4, 1..=6).collect_vec();
2808/// assert_eq!(
2809/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2810/// &[
2811/// &[1, 2, 3, 4],
2812/// &[1, 2, 3, 5],
2813/// &[1, 2, 4, 5],
2814/// &[1, 3, 4, 5],
2815/// &[2, 3, 4, 5],
2816/// &[1, 2, 3, 6],
2817/// &[1, 2, 4, 6],
2818/// &[1, 3, 4, 6],
2819/// &[2, 3, 4, 6],
2820/// &[1, 2, 5, 6],
2821/// &[1, 3, 5, 6],
2822/// &[2, 3, 5, 6],
2823/// &[1, 4, 5, 6],
2824/// &[2, 4, 5, 6],
2825/// &[3, 4, 5, 6]
2826/// ]
2827/// );
2828/// ```
2829#[inline]
2830pub fn exhaustive_ordered_unique_vecs_fixed_length<I: Iterator>(
2831 k: u64,
2832 xs: I,
2833) -> ExhaustiveOrderedUniqueCollections<I, Vec<I::Item>>
2834where
2835 I::Item: Clone,
2836{
2837 exhaustive_ordered_unique_vecs_length_inclusive_range(k, k, xs)
2838}
2839
2840/// Generates [`Vec`]s with elements from a single iterator, such that each [`Vec`] has no repeated
2841/// elements, and the elements in each [`Vec`] are ordered the same way as they are in the source
2842/// iterator.
2843///
2844/// The source iterator should not repeat any elements, but this is not enforced.
2845///
2846/// The iterator should be finite; if it is infinite, only prefixes of the iterator will be
2847/// generated.
2848///
2849/// If the input iterator is infinite, the output length is also infinite.
2850///
2851/// If the input iterator length is $n$, the output length is $2^n$.
2852///
2853/// If `xs` is empty, the output consists of a single empty [`Vec`].
2854///
2855/// # Examples
2856/// ```
2857/// use itertools::Itertools;
2858/// use malachite_base::vecs::exhaustive::exhaustive_ordered_unique_vecs;
2859///
2860/// let xss = exhaustive_ordered_unique_vecs(1..=4).collect_vec();
2861/// assert_eq!(
2862/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2863/// &[
2864/// &[][..],
2865/// &[1],
2866/// &[2],
2867/// &[1, 2],
2868/// &[3],
2869/// &[1, 3],
2870/// &[2, 3],
2871/// &[1, 2, 3],
2872/// &[4],
2873/// &[1, 4],
2874/// &[2, 4],
2875/// &[1, 2, 4],
2876/// &[3, 4],
2877/// &[1, 3, 4],
2878/// &[2, 3, 4],
2879/// &[1, 2, 3, 4]
2880/// ]
2881/// );
2882/// ```
2883#[inline]
2884pub fn exhaustive_ordered_unique_vecs<I: Iterator>(
2885 xs: I,
2886) -> ExhaustiveOrderedUniqueCollections<I, Vec<I::Item>>
2887where
2888 I::Item: Clone,
2889{
2890 exhaustive_ordered_unique_vecs_length_inclusive_range(0, u64::MAX, xs)
2891}
2892
2893/// Generates [`Vec`]s with a mininum length, with elements from a single iterator, such that each
2894/// [`Vec`] has no repeated elements, and the elements in each [`Vec`] are ordered the same way as
2895/// they are in the source iterator.
2896///
2897/// The source iterator should not repeat any elements, but this is not enforced.
2898///
2899/// The iterator should be finite; if it is infinite, only prefixes of the iterator will be
2900/// generated.
2901///
2902/// If the input iterator is infinite, the output length is also infinite.
2903///
2904/// If the input iterator length is $n$ and the `min_length` is $\ell$, the output length is
2905/// $$
2906/// \sum_{i=\ell}^n \binom{n}{i}.
2907/// $$
2908///
2909/// # Examples
2910/// ```
2911/// use itertools::Itertools;
2912/// use malachite_base::vecs::exhaustive::exhaustive_ordered_unique_vecs_min_length;
2913///
2914/// let xss = exhaustive_ordered_unique_vecs_min_length(2, 1..=4).collect_vec();
2915/// assert_eq!(
2916/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2917/// &[
2918/// &[1, 2][..],
2919/// &[1, 3],
2920/// &[2, 3],
2921/// &[1, 2, 3],
2922/// &[1, 4],
2923/// &[2, 4],
2924/// &[1, 2, 4],
2925/// &[3, 4],
2926/// &[1, 3, 4],
2927/// &[2, 3, 4],
2928/// &[1, 2, 3, 4]
2929/// ]
2930/// );
2931/// ```
2932#[inline]
2933pub fn exhaustive_ordered_unique_vecs_min_length<I: Iterator>(
2934 min_length: u64,
2935 xs: I,
2936) -> ExhaustiveOrderedUniqueCollections<I, Vec<I::Item>>
2937where
2938 I::Item: Clone,
2939{
2940 exhaustive_ordered_unique_vecs_length_inclusive_range(min_length, u64::MAX, xs)
2941}
2942
2943/// Generates [`Vec`]s, with lengths in a range $[a, b)$, with elements from a single iterator, such
2944/// that each [`Vec`] has no repeated elements, and the elements in each [`Vec`] are ordered the
2945/// same way as they are in the source iterator.
2946///
2947/// The source iterator should not repeat any elements, but this is not enforced.
2948///
2949/// The iterator should be finite; if it is infinite, only prefixes of the iterator will be
2950/// generated.
2951///
2952/// If $a \leq b$, the output is empty.
2953///
2954/// If $a = 0$ and $b = 1$, the output consists of a single empty [`Vec`].
2955///
2956/// If the input iterator is infinite and $0 < a < b$, the output length is also infinite.
2957///
2958/// If the input iterator length is $n$, the output length is
2959/// $$
2960/// \sum_{i=a}^{b - 1} \binom{n}{i}.
2961/// $$
2962///
2963/// # Examples
2964/// ```
2965/// use itertools::Itertools;
2966/// use malachite_base::vecs::exhaustive::exhaustive_ordered_unique_vecs_length_range;
2967///
2968/// let xss = exhaustive_ordered_unique_vecs_length_range(2, 4, 1..=4).collect_vec();
2969/// assert_eq!(
2970/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2971/// &[
2972/// &[1, 2][..],
2973/// &[1, 3],
2974/// &[2, 3],
2975/// &[1, 2, 3],
2976/// &[1, 4],
2977/// &[2, 4],
2978/// &[1, 2, 4],
2979/// &[3, 4],
2980/// &[1, 3, 4],
2981/// &[2, 3, 4]
2982/// ]
2983/// );
2984/// ```
2985#[inline]
2986pub fn exhaustive_ordered_unique_vecs_length_range<I: Iterator>(
2987 a: u64,
2988 b: u64,
2989 xs: I,
2990) -> ExhaustiveOrderedUniqueCollections<I, Vec<I::Item>>
2991where
2992 I::Item: Clone,
2993{
2994 if a >= b {
2995 ExhaustiveOrderedUniqueCollections::None
2996 } else {
2997 exhaustive_ordered_unique_vecs_length_inclusive_range(a, b - 1, xs)
2998 }
2999}
3000
3001/// Generates [`Vec`]s, with lengths in a range $[a, b]$, with elements from a single iterator, such
3002/// that each [`Vec`] has no repeated elements, and the elements in each [`Vec`] are ordered the
3003/// same way as they are in the source iterator.
3004///
3005/// The [`Vec`]s are ordered lexicographically with respect to the order of the element iterator.
3006///
3007/// The source iterator should not repeat any elements, but this is not enforced.
3008///
3009/// The iterator should be finite; if it is infinite, only prefixes of the iterator will be
3010/// generated.
3011///
3012/// If $a < b$, the output is empty.
3013///
3014/// If $a = b = 0$, the output consists of a single empty [`Vec`].
3015///
3016/// If the input iterator is infinite and $0 < a \leq b$, the output length is also infinite.
3017///
3018/// If the input iterator length is $n$, the output length is
3019/// $$
3020/// \sum_{i=a}^b \binom{n}{i}.
3021/// $$
3022///
3023/// # Examples
3024/// ```
3025/// use itertools::Itertools;
3026/// use malachite_base::vecs::exhaustive::exhaustive_ordered_unique_vecs_length_inclusive_range;
3027///
3028/// let xss = exhaustive_ordered_unique_vecs_length_inclusive_range(2, 3, 1..=4).collect_vec();
3029/// assert_eq!(
3030/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
3031/// &[
3032/// &[1, 2][..],
3033/// &[1, 3],
3034/// &[2, 3],
3035/// &[1, 2, 3],
3036/// &[1, 4],
3037/// &[2, 4],
3038/// &[1, 2, 4],
3039/// &[3, 4],
3040/// &[1, 3, 4],
3041/// &[2, 3, 4]
3042/// ]
3043/// );
3044/// ```
3045#[inline]
3046pub fn exhaustive_ordered_unique_vecs_length_inclusive_range<I: Iterator>(
3047 a: u64,
3048 b: u64,
3049 xs: I,
3050) -> ExhaustiveOrderedUniqueCollections<I, Vec<I::Item>>
3051where
3052 I::Item: Clone,
3053{
3054 ExhaustiveOrderedUniqueCollections::new(a, b, xs)
3055}
3056
3057fn fixed_length_unique_indices_helper(indices: &mut [usize], used: &mut [bool]) -> bool {
3058 let n = used.len();
3059 let k = indices.len();
3060 assert!(k <= n);
3061 for i in (0..k).rev() {
3062 let x = indices[i];
3063 used[x] = false;
3064 for y in x + 1..n {
3065 if !used[y] {
3066 indices[i] = y;
3067 used[y] = true;
3068 let mut p = 0;
3069 for j in &mut indices[i + 1..k] {
3070 while used[p] {
3071 p += 1;
3072 }
3073 *j = p;
3074 used[p] = true;
3075 }
3076 return false;
3077 }
3078 }
3079 }
3080 true
3081}
3082
3083#[doc(hidden)]
3084#[derive(Clone, Debug)]
3085pub struct UniqueIndices {
3086 pub done: bool,
3087 first: bool,
3088 indices: Vec<usize>,
3089 pub used: Vec<bool>,
3090}
3091
3092impl UniqueIndices {
3093 #[doc(hidden)]
3094 pub const fn get_n(&self) -> usize {
3095 self.used.len()
3096 }
3097
3098 #[doc(hidden)]
3099 pub fn increment_n(&mut self) {
3100 self.used.push(false);
3101 }
3102}
3103
3104impl Iterator for UniqueIndices {
3105 type Item = Vec<usize>;
3106
3107 fn next(&mut self) -> Option<Vec<usize>> {
3108 if self.done {
3109 None
3110 } else if self.first {
3111 self.first = false;
3112 Some(self.indices.clone())
3113 } else if fixed_length_unique_indices_helper(&mut self.indices, &mut self.used) {
3114 self.done = true;
3115 None
3116 } else {
3117 Some(self.indices.clone())
3118 }
3119 }
3120}
3121
3122#[doc(hidden)]
3123pub fn unique_indices(n: usize, k: usize) -> UniqueIndices {
3124 UniqueIndices {
3125 done: n == 0 && k != 0,
3126 first: true,
3127 indices: (0..k).collect_vec(),
3128 used: repeat_n(true, k)
3129 .chain(repeat_n(false, n - k))
3130 .collect_vec(),
3131 }
3132}
3133
3134/// Generates all [`Vec`]s of elements from an iterator, where the [`Vec`]s are of a fixed length
3135/// and have no repetitions.
3136#[derive(Clone)]
3137pub struct LexUniqueVecsFixedLength<I: Iterator>
3138where
3139 I::Item: Clone,
3140{
3141 first: bool,
3142 xs: IteratorCache<I>,
3143 indices: UniqueIndices,
3144}
3145
3146impl<I: Iterator> Iterator for LexUniqueVecsFixedLength<I>
3147where
3148 I::Item: Clone,
3149{
3150 type Item = Vec<I::Item>;
3151
3152 fn next(&mut self) -> Option<Self::Item> {
3153 if self.first {
3154 if !self.indices.used.is_empty() && self.xs.get(self.indices.get_n() - 1).is_none() {
3155 self.indices.done = true;
3156 }
3157 self.first = false;
3158 }
3159 if self.xs.get(self.indices.get_n()).is_some() {
3160 self.indices.increment_n();
3161 }
3162 self.indices.next().map(|indices| {
3163 indices
3164 .into_iter()
3165 .map(|i| self.xs.assert_get(i).clone())
3166 .collect_vec()
3167 })
3168 }
3169}
3170
3171/// Generates [`Vec`]s of a given length with elements from a single iterator, such that each
3172/// [`Vec`] has no repeated elements.
3173///
3174/// The source iterator should not repeat any elements, but this is not enforced.
3175///
3176/// The order is lexicographic with respect to the order of the element iterator.
3177///
3178/// If $k$ is 0, the output length is 1.
3179///
3180/// If $k$ is nonzero and the input iterator is infinite, the output length is also infinite.
3181///
3182/// If $k$ is nonzero and the input iterator length is $n$, the output length is
3183/// $$
3184/// (n)_ k = \prod_ {i=0}^{k-1}(n - i) = frac{n!}{(n-k)!}.
3185/// $$
3186///
3187/// If $k$ is 0, the output consists of one empty [`Vec`].
3188///
3189/// If `xs` is empty, the output is also empty, unless $k$ is 0.
3190///
3191/// # Examples
3192/// ```
3193/// use itertools::Itertools;
3194/// use malachite_base::vecs::exhaustive::lex_unique_vecs_fixed_length;
3195///
3196/// let xss = lex_unique_vecs_fixed_length(4, 1..=6)
3197/// .take(20)
3198/// .collect_vec();
3199/// assert_eq!(
3200/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
3201/// &[
3202/// &[1, 2, 3, 4],
3203/// &[1, 2, 3, 5],
3204/// &[1, 2, 3, 6],
3205/// &[1, 2, 4, 3],
3206/// &[1, 2, 4, 5],
3207/// &[1, 2, 4, 6],
3208/// &[1, 2, 5, 3],
3209/// &[1, 2, 5, 4],
3210/// &[1, 2, 5, 6],
3211/// &[1, 2, 6, 3],
3212/// &[1, 2, 6, 4],
3213/// &[1, 2, 6, 5],
3214/// &[1, 3, 2, 4],
3215/// &[1, 3, 2, 5],
3216/// &[1, 3, 2, 6],
3217/// &[1, 3, 4, 2],
3218/// &[1, 3, 4, 5],
3219/// &[1, 3, 4, 6],
3220/// &[1, 3, 5, 2],
3221/// &[1, 3, 5, 4],
3222/// ]
3223/// );
3224/// ```
3225#[inline]
3226pub fn lex_unique_vecs_fixed_length<I: Iterator>(k: u64, xs: I) -> LexUniqueVecsFixedLength<I>
3227where
3228 I::Item: Clone,
3229{
3230 let k = usize::exact_from(k);
3231 LexUniqueVecsFixedLength {
3232 first: true,
3233 xs: IteratorCache::new(xs),
3234 // Initial n is k, but will grow to reach actual n (or forever, if n is infinite)
3235 indices: unique_indices(k, k),
3236 }
3237}
3238
3239/// Generates all [`Vec`]s of elements from an iterator in shortlex order, where the [`Vec`]s have
3240/// no repetitions.
3241#[derive(Clone)]
3242pub struct ShortlexUniqueVecs<I: Clone + Iterator>
3243where
3244 I::Item: Clone,
3245{
3246 current_len: u64,
3247 max_len: u64,
3248 xs: I,
3249 current_xss: LexUniqueVecsFixedLength<I>,
3250}
3251
3252impl<I: Clone + Iterator> ShortlexUniqueVecs<I>
3253where
3254 I::Item: Clone,
3255{
3256 fn new(a: u64, b: u64, xs: I) -> Self {
3257 Self {
3258 current_len: a,
3259 max_len: b,
3260 xs: xs.clone(),
3261 current_xss: lex_unique_vecs_fixed_length(a, xs),
3262 }
3263 }
3264}
3265
3266impl<I: Clone + Iterator> Iterator for ShortlexUniqueVecs<I>
3267where
3268 I::Item: Clone,
3269{
3270 type Item = Vec<I::Item>;
3271
3272 fn next(&mut self) -> Option<Vec<I::Item>> {
3273 if self.current_len > self.max_len {
3274 return None;
3275 }
3276 if let Some(next) = self.current_xss.next() {
3277 Some(next)
3278 } else {
3279 self.current_len += 1;
3280 if self.current_len > self.max_len {
3281 return None;
3282 }
3283 self.current_xss = lex_unique_vecs_fixed_length(self.current_len, self.xs.clone());
3284 if let Some(next) = self.current_xss.next() {
3285 Some(next)
3286 } else {
3287 // Prevent any further iteration
3288 self.max_len = 0;
3289 self.current_len = 1;
3290 None
3291 }
3292 }
3293 }
3294}
3295
3296/// Generates [`Vec`]s with elements from a single iterator, such that each [`Vec`] has no repeated
3297/// elements.
3298///
3299/// The [`Vec`]s are generated in order of increasing length, and within each length they are
3300/// ordered lexicographically with respect to the order of the element iterator.
3301///
3302/// The source iterator should not repeat any elements, but this is not enforced.
3303///
3304/// The iterator should be finite; if it is infinite, [`Vec`]s of length 2 and above will never be
3305/// generated.
3306///
3307/// If the input iterator is infinite, the output length is also infinite.
3308///
3309/// If the input iterator length is $n$, the output length is
3310/// $$
3311/// \sum_ {k=0}^n \frac{n!}{k!}
3312/// $$
3313/// $$
3314/// = \\begin{cases}
3315/// 1 & \text{if} \\quad n = 0, \\\\
3316/// 2 & \text{if} \\quad n = 1, \\\\
3317/// \operatorname{round}(en!) & \\text{otherwise}.
3318/// \\end{cases}
3319/// $$
3320///
3321/// See <https://oeis.org/A000522>.
3322///
3323/// If `xs` is empty, the output consists of a single empty [`Vec`].
3324///
3325/// # Examples
3326/// ```
3327/// use itertools::Itertools;
3328/// use malachite_base::vecs::exhaustive::shortlex_unique_vecs;
3329///
3330/// let xss = shortlex_unique_vecs(1..=4).take(20).collect_vec();
3331/// assert_eq!(
3332/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
3333/// &[
3334/// &[][..],
3335/// &[1],
3336/// &[2],
3337/// &[3],
3338/// &[4],
3339/// &[1, 2],
3340/// &[1, 3],
3341/// &[1, 4],
3342/// &[2, 1],
3343/// &[2, 3],
3344/// &[2, 4],
3345/// &[3, 1],
3346/// &[3, 2],
3347/// &[3, 4],
3348/// &[4, 1],
3349/// &[4, 2],
3350/// &[4, 3],
3351/// &[1, 2, 3],
3352/// &[1, 2, 4],
3353/// &[1, 3, 2]
3354/// ]
3355/// );
3356/// ```
3357#[inline]
3358pub fn shortlex_unique_vecs<I: Clone + Iterator>(xs: I) -> ShortlexUniqueVecs<I>
3359where
3360 I::Item: Clone,
3361{
3362 shortlex_unique_vecs_length_inclusive_range(0, u64::MAX, xs)
3363}
3364
3365/// Generates [`Vec`]s with a mininum length, with elements from a single iterator, such that each
3366/// [`Vec`] has no repeated elements.
3367///
3368/// The [`Vec`]s are generated in order of increasing length, and within each length they are
3369/// ordered lexicographically with respect to the order of the element iterator.
3370///
3371/// The source iterator should not repeat any elements, but this is not enforced.
3372///
3373/// The iterator should be finite; if it is infinite, [`Vec`]s of length `\max(2, \ell + 1)` and
3374/// above will never be generated.
3375///
3376/// If the input iterator is infinite, the output length is also infinite.
3377///
3378/// If the input iterator length is $n$ and the `min_length` is $\ell$, the output length is
3379/// $$
3380/// \sum_ {k=\ell}^n \frac{n!}{k!}.
3381/// $$
3382///
3383/// # Examples
3384/// ```
3385/// use itertools::Itertools;
3386/// use malachite_base::vecs::exhaustive::shortlex_unique_vecs_min_length;
3387///
3388/// let xss = shortlex_unique_vecs_min_length(2, 1..=4)
3389/// .take(20)
3390/// .collect_vec();
3391/// assert_eq!(
3392/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
3393/// &[
3394/// &[1, 2][..],
3395/// &[1, 3],
3396/// &[1, 4],
3397/// &[2, 1],
3398/// &[2, 3],
3399/// &[2, 4],
3400/// &[3, 1],
3401/// &[3, 2],
3402/// &[3, 4],
3403/// &[4, 1],
3404/// &[4, 2],
3405/// &[4, 3],
3406/// &[1, 2, 3],
3407/// &[1, 2, 4],
3408/// &[1, 3, 2],
3409/// &[1, 3, 4],
3410/// &[1, 4, 2],
3411/// &[1, 4, 3],
3412/// &[2, 1, 3],
3413/// &[2, 1, 4]
3414/// ]
3415/// );
3416/// ```
3417#[inline]
3418pub fn shortlex_unique_vecs_min_length<I: Clone + Iterator>(
3419 min_length: u64,
3420 xs: I,
3421) -> ShortlexUniqueVecs<I>
3422where
3423 I::Item: Clone,
3424{
3425 shortlex_unique_vecs_length_inclusive_range(min_length, u64::MAX, xs)
3426}
3427
3428/// Generates [`Vec`]s, with lengths in a range $[a, b)$, with elements from a single iterator, such
3429/// that each [`Vec`] has no repeated elements.
3430///
3431/// The [`Vec`]s are generated in order of increasing length, and within each length they are
3432/// ordered lexicographically with respect to the order of the element iterator.
3433///
3434/// The source iterator should not repeat any elements, but this is not enforced.
3435///
3436/// The iterator should be finite; if it is infinite, [`Vec`]s of length `\max(2, a + 1)` and above
3437/// will never be generated.
3438///
3439/// If $a \leq b$, the output is empty.
3440///
3441/// If $a = 0$ and $b = 1$, the output consists of a single empty [`Vec`].
3442///
3443/// If the input iterator is infinite and $0 < a < b$, the output length is also infinite.
3444///
3445/// If the input iterator length is $n$, the output length is
3446/// $$
3447/// \sum_{i=a}^{b - 1} \frac{n!}{k!}.
3448/// $$
3449///
3450/// # Examples
3451/// ```
3452/// use itertools::Itertools;
3453/// use malachite_base::vecs::exhaustive::shortlex_unique_vecs_length_range;
3454///
3455/// let xss = shortlex_unique_vecs_length_range(2, 4, 1..=4)
3456/// .take(20)
3457/// .collect_vec();
3458/// assert_eq!(
3459/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
3460/// &[
3461/// &[1, 2][..],
3462/// &[1, 3],
3463/// &[1, 4],
3464/// &[2, 1],
3465/// &[2, 3],
3466/// &[2, 4],
3467/// &[3, 1],
3468/// &[3, 2],
3469/// &[3, 4],
3470/// &[4, 1],
3471/// &[4, 2],
3472/// &[4, 3],
3473/// &[1, 2, 3],
3474/// &[1, 2, 4],
3475/// &[1, 3, 2],
3476/// &[1, 3, 4],
3477/// &[1, 4, 2],
3478/// &[1, 4, 3],
3479/// &[2, 1, 3],
3480/// &[2, 1, 4]
3481/// ]
3482/// );
3483/// ```
3484#[inline]
3485pub fn shortlex_unique_vecs_length_range<I: Clone + Iterator>(
3486 mut a: u64,
3487 mut b: u64,
3488 xs: I,
3489) -> ShortlexUniqueVecs<I>
3490where
3491 I::Item: Clone,
3492{
3493 if b == 0 {
3494 // Transform an empty (x, 0) range into (2, 1), which is also empty but doesn't cause
3495 // overflow
3496 a = 2;
3497 b = 1;
3498 }
3499 shortlex_unique_vecs_length_inclusive_range(a, b - 1, xs)
3500}
3501
3502/// Generates [`Vec`]s, with lengths in a range $[a, b]$, with elements from a single iterator, such
3503/// that each [`Vec`] has no repeated elements.
3504///
3505/// The [`Vec`]s are generated in order of increasing length, and within each length they are
3506/// ordered lexicographically with respect to the order of the element iterator.
3507///
3508/// The source iterator should not repeat any elements, but this is not enforced.
3509///
3510/// The iterator should be finite; if it is infinite, [`Vec`]s of length `\max(2, a + 1)` and above
3511/// will never be generated.
3512///
3513/// If $a < b$, the output is empty.
3514///
3515/// If $a = b = 0$, the output consists of a single empty [`Vec`].
3516///
3517/// If the input iterator is infinite and $0 < a \leq b$, the output length is also infinite.
3518///
3519/// If the input iterator length is $n$, the output length is
3520/// $$
3521/// \sum_{i=a}^b \frac{n!}{k!}.
3522/// $$
3523///
3524/// # Examples
3525/// ```
3526/// use itertools::Itertools;
3527/// use malachite_base::vecs::exhaustive::shortlex_unique_vecs_length_inclusive_range;
3528///
3529/// let xss = shortlex_unique_vecs_length_inclusive_range(2, 3, 1..=4)
3530/// .take(20)
3531/// .collect_vec();
3532/// assert_eq!(
3533/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
3534/// &[
3535/// &[1, 2][..],
3536/// &[1, 3],
3537/// &[1, 4],
3538/// &[2, 1],
3539/// &[2, 3],
3540/// &[2, 4],
3541/// &[3, 1],
3542/// &[3, 2],
3543/// &[3, 4],
3544/// &[4, 1],
3545/// &[4, 2],
3546/// &[4, 3],
3547/// &[1, 2, 3],
3548/// &[1, 2, 4],
3549/// &[1, 3, 2],
3550/// &[1, 3, 4],
3551/// &[1, 4, 2],
3552/// &[1, 4, 3],
3553/// &[2, 1, 3],
3554/// &[2, 1, 4]
3555/// ]
3556/// );
3557/// ```
3558#[inline]
3559pub fn shortlex_unique_vecs_length_inclusive_range<I: Clone + Iterator>(
3560 a: u64,
3561 b: u64,
3562 xs: I,
3563) -> ShortlexUniqueVecs<I>
3564where
3565 I::Item: Clone,
3566{
3567 ShortlexUniqueVecs::new(a, b, xs)
3568}
3569
3570fn compare_indexed_vecs_lex<T>(xs: &[(usize, T)], ys: &[(usize, T)]) -> Ordering {
3571 let xs_len = xs.len();
3572 let ys_len = ys.len();
3573 for i in 0..min(xs_len, ys_len) {
3574 let o = xs[i].0.cmp(&ys[i].0);
3575 if o != Equal {
3576 return o;
3577 }
3578 }
3579 xs_len.cmp(&ys_len)
3580}
3581
3582/// Generates all collections of elements from an iterator in lexicographic order, where the
3583/// collections have no repetitions.
3584#[derive(Clone)]
3585pub struct LexUniqueVecs<I: Clone + Iterator>
3586where
3587 I::Item: Clone,
3588{
3589 done: bool,
3590 first: bool,
3591 min: usize,
3592 max: usize,
3593 xs_for_prefix: I,
3594 xs: I,
3595 phase_1_vec: Option<Vec<I::Item>>,
3596 xsss: Vec<LexUniqueVecsFixedLength<Zip<RangeFrom<usize>, I>>>,
3597 next_xss: Vec<Option<Vec<(usize, I::Item)>>>,
3598}
3599
3600impl<I: Clone + Iterator> Iterator for LexUniqueVecs<I>
3601where
3602 I::Item: Clone,
3603{
3604 type Item = Vec<I::Item>;
3605
3606 fn next(&mut self) -> Option<Vec<I::Item>> {
3607 if self.done {
3608 return None;
3609 }
3610 if self.first {
3611 self.first = false;
3612 return self.phase_1_vec.clone();
3613 }
3614 if let Some(prefix) = self.phase_1_vec.as_mut()
3615 && prefix.len() < self.max
3616 {
3617 if let Some(x) = self.xs_for_prefix.next() {
3618 prefix.push(x);
3619 return Some(prefix.clone());
3620 }
3621 self.max = prefix.len();
3622 }
3623 if self.phase_1_vec.is_some() {
3624 for k in self.min..=self.max {
3625 let mut xss =
3626 lex_unique_vecs_fixed_length(u64::exact_from(k), (0..).zip(self.xs.clone()));
3627 // Skip over first Vec of length k, which was already generated in phase 1
3628 xss.next();
3629 self.next_xss.push(xss.next());
3630 self.xsss.push(xss);
3631 }
3632 self.phase_1_vec = None;
3633 }
3634 let mut min_i = None;
3635 let mut i_done = None;
3636 for i in 0..self.next_xss.len() {
3637 let choose = if let Some(xs) = &self.next_xss[i] {
3638 if let Some(min_i) = min_i {
3639 let ys: &Option<Vec<(usize, I::Item)>> = &self.next_xss[min_i];
3640 compare_indexed_vecs_lex(xs, ys.as_ref().unwrap()) == Less
3641 } else {
3642 true
3643 }
3644 } else {
3645 i_done = Some(i);
3646 false
3647 };
3648 if choose {
3649 min_i = Some(i);
3650 }
3651 }
3652 if let Some(i) = min_i {
3653 self.next_xss.push(self.xsss[i].next());
3654 let xs = self
3655 .next_xss
3656 .swap_remove(i)
3657 .map(|xs| xs.into_iter().map(|p| p.1).collect());
3658 if let Some(i_done) = i_done {
3659 self.xsss.remove(i_done);
3660 self.next_xss.remove(i_done);
3661 }
3662 xs
3663 } else {
3664 self.done = true;
3665 None
3666 }
3667 }
3668}
3669
3670/// Generates [`Vec`]s with elements from a single iterator, such that each [`Vec`] has no repeated
3671/// elements.
3672///
3673/// The [`Vec`]s are ordered lexicographically with respect to the order of the element iterator.
3674///
3675/// The source iterator should not repeat any elements, but this is not enforced.
3676///
3677/// The iterator should be finite; if it is infinite, only prefixes of the iterator will be
3678/// generated.
3679///
3680/// If the input iterator is infinite, the output length is also infinite.
3681///
3682/// If the input iterator length is $n$, the output length is
3683/// $$
3684/// \sum_ {k=0}^n \frac{n!}{k!}
3685/// $$
3686/// $$
3687/// = \\begin{cases}
3688/// 1 & \text{if} \\quad n = 0, \\\\
3689/// 2 & \text{if} \\quad n = 1, \\\\
3690/// \operatorname{round}(en!) & \\text{otherwise}.
3691/// \\end{cases}
3692/// $$
3693///
3694/// See <https://oeis.org/A000522>.
3695///
3696/// If `xs` is empty, the output consists of a single empty [`Vec`].
3697///
3698/// # Examples
3699/// ```
3700/// use itertools::Itertools;
3701/// use malachite_base::vecs::exhaustive::lex_unique_vecs;
3702///
3703/// let xss = lex_unique_vecs(1..=4).take(20).collect_vec();
3704/// assert_eq!(
3705/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
3706/// &[
3707/// &[][..],
3708/// &[1],
3709/// &[1, 2],
3710/// &[1, 2, 3],
3711/// &[1, 2, 3, 4],
3712/// &[1, 2, 4],
3713/// &[1, 2, 4, 3],
3714/// &[1, 3],
3715/// &[1, 3, 2],
3716/// &[1, 3, 2, 4],
3717/// &[1, 3, 4],
3718/// &[1, 3, 4, 2],
3719/// &[1, 4],
3720/// &[1, 4, 2],
3721/// &[1, 4, 2, 3],
3722/// &[1, 4, 3],
3723/// &[1, 4, 3, 2],
3724/// &[2],
3725/// &[2, 1],
3726/// &[2, 1, 3]
3727/// ]
3728/// );
3729/// ```
3730#[inline]
3731pub fn lex_unique_vecs<I: Clone + Iterator>(xs: I) -> LexUniqueVecs<I>
3732where
3733 I::Item: Clone,
3734{
3735 lex_unique_vecs_length_inclusive_range(0, u64::MAX, xs)
3736}
3737
3738/// Generates [`Vec`]s with a mininum length, with elements from a single iterator, such that each
3739/// [`Vec`] has no repeated elements.
3740///
3741/// The [`Vec`]s are ordered lexicographically with respect to the order of the element iterator.
3742///
3743/// The source iterator should not repeat any elements, but this is not enforced.
3744///
3745/// The iterator should be finite; if it is infinite, only prefixes of the iterator will be
3746/// generated.
3747///
3748/// If the input iterator is infinite, the output length is also infinite.
3749///
3750/// If the input iterator length is $n$ and the `min_length` is $\ell$, the output length is
3751/// $$
3752/// \sum_{i=\ell}^n \frac{n!}{k!}.
3753/// $$
3754///
3755/// # Examples
3756/// ```
3757/// use itertools::Itertools;
3758/// use malachite_base::vecs::exhaustive::lex_unique_vecs_min_length;
3759///
3760/// let xss = lex_unique_vecs_min_length(2, 1..=4).take(20).collect_vec();
3761/// assert_eq!(
3762/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
3763/// &[
3764/// &[1, 2][..],
3765/// &[1, 2, 3],
3766/// &[1, 2, 3, 4],
3767/// &[1, 2, 4],
3768/// &[1, 2, 4, 3],
3769/// &[1, 3],
3770/// &[1, 3, 2],
3771/// &[1, 3, 2, 4],
3772/// &[1, 3, 4],
3773/// &[1, 3, 4, 2],
3774/// &[1, 4],
3775/// &[1, 4, 2],
3776/// &[1, 4, 2, 3],
3777/// &[1, 4, 3],
3778/// &[1, 4, 3, 2],
3779/// &[2, 1],
3780/// &[2, 1, 3],
3781/// &[2, 1, 3, 4],
3782/// &[2, 1, 4],
3783/// &[2, 1, 4, 3]
3784/// ]
3785/// );
3786/// ```
3787#[inline]
3788pub fn lex_unique_vecs_min_length<I: Clone + Iterator>(min_length: u64, xs: I) -> LexUniqueVecs<I>
3789where
3790 I::Item: Clone,
3791{
3792 lex_unique_vecs_length_inclusive_range(min_length, u64::MAX, xs)
3793}
3794
3795/// Generates [`Vec`]s, with lengths in a range $[a, b)$, with elements from a single iterator, such
3796/// that each [`Vec`] has no repeated elements.
3797///
3798/// The [`Vec`]s are ordered lexicographically with respect to the order of the element iterator.
3799///
3800/// The source iterator should not repeat any elements, but this is not enforced.
3801///
3802/// The iterator should be finite; if it is infinite, only prefixes of the iterator will be
3803/// generated.
3804///
3805/// If $a \leq b$, the output is empty.
3806///
3807/// If $a = 0$ and $b = 1$, the output consists of a single empty [`Vec`].
3808///
3809/// If the input iterator is infinite and $0 < a < b$, the output length is also infinite.
3810///
3811/// If the input iterator length is $n$, the output length is
3812/// $$
3813/// \sum_{i=a}^{b - 1} \frac{n!}{k!}.
3814/// $$
3815///
3816/// # Examples
3817/// ```
3818/// use itertools::Itertools;
3819/// use malachite_base::vecs::exhaustive::lex_unique_vecs_length_range;
3820///
3821/// let xss = lex_unique_vecs_length_range(2, 4, 1..=4)
3822/// .take(20)
3823/// .collect_vec();
3824/// assert_eq!(
3825/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
3826/// &[
3827/// &[1, 2][..],
3828/// &[1, 2, 3],
3829/// &[1, 2, 4],
3830/// &[1, 3],
3831/// &[1, 3, 2],
3832/// &[1, 3, 4],
3833/// &[1, 4],
3834/// &[1, 4, 2],
3835/// &[1, 4, 3],
3836/// &[2, 1],
3837/// &[2, 1, 3],
3838/// &[2, 1, 4],
3839/// &[2, 3],
3840/// &[2, 3, 1],
3841/// &[2, 3, 4],
3842/// &[2, 4],
3843/// &[2, 4, 1],
3844/// &[2, 4, 3],
3845/// &[3, 1],
3846/// &[3, 1, 2]
3847/// ]
3848/// );
3849/// ```
3850#[inline]
3851pub fn lex_unique_vecs_length_range<I: Clone + Iterator>(
3852 mut a: u64,
3853 mut b: u64,
3854 xs: I,
3855) -> LexUniqueVecs<I>
3856where
3857 I::Item: Clone,
3858{
3859 if b == 0 {
3860 // Transform an empty (x, 0) range into (2, 1), which is also empty but doesn't cause
3861 // overflow
3862 a = 2;
3863 b = 1;
3864 }
3865 lex_unique_vecs_length_inclusive_range(a, b - 1, xs)
3866}
3867
3868/// Generates [`Vec`]s with a mininum length, with elements from a single iterator, such that each
3869/// [`Vec`] has no repeated elements.
3870///
3871/// The [`Vec`]s are ordered lexicographically with respect to the order of the element iterator.
3872///
3873/// The source iterator should not repeat any elements, but this is not enforced.
3874///
3875/// The iterator should be finite; if it is infinite, only prefixes of the iterator will be
3876/// generated.
3877///
3878/// If the input iterator is infinite, the output length is also infinite.
3879///
3880/// If the input iterator length is $n$ and the `min_length` is $\ell$, the output length is
3881/// $$
3882/// \sum_{i=\ell}^n \frac{n!}{k!}.
3883/// $$
3884///
3885/// # Examples
3886/// ```
3887/// use itertools::Itertools;
3888/// use malachite_base::vecs::exhaustive::lex_unique_vecs_min_length;
3889///
3890/// let xss = lex_unique_vecs_min_length(2, 1..=4).take(20).collect_vec();
3891/// assert_eq!(
3892/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
3893/// &[
3894/// &[1, 2][..],
3895/// &[1, 2, 3],
3896/// &[1, 2, 3, 4],
3897/// &[1, 2, 4],
3898/// &[1, 2, 4, 3],
3899/// &[1, 3],
3900/// &[1, 3, 2],
3901/// &[1, 3, 2, 4],
3902/// &[1, 3, 4],
3903/// &[1, 3, 4, 2],
3904/// &[1, 4],
3905/// &[1, 4, 2],
3906/// &[1, 4, 2, 3],
3907/// &[1, 4, 3],
3908/// &[1, 4, 3, 2],
3909/// &[2, 1],
3910/// &[2, 1, 3],
3911/// &[2, 1, 3, 4],
3912/// &[2, 1, 4],
3913/// &[2, 1, 4, 3]
3914/// ]
3915/// );
3916/// ```
3917#[inline]
3918pub fn lex_unique_vecs_length_inclusive_range<I: Clone + Iterator>(
3919 a: u64,
3920 b: u64,
3921 xs: I,
3922) -> LexUniqueVecs<I>
3923where
3924 I::Item: Clone,
3925{
3926 let a = usize::exact_from(a);
3927 let b = usize::exact_from(b);
3928 let mut xs_for_prefix = xs.clone();
3929 let phase_1_vec = (&mut xs_for_prefix).take(a).collect_vec();
3930 LexUniqueVecs {
3931 done: a > b || phase_1_vec.len() < a,
3932 first: true,
3933 min: a,
3934 max: b,
3935 xs_for_prefix,
3936 xs,
3937 phase_1_vec: Some(phase_1_vec),
3938 xsss: Vec::new(),
3939 next_xss: Vec::new(),
3940 }
3941}
3942
3943#[doc(hidden)]
3944#[derive(Clone)]
3945pub struct ExhaustiveUniqueVecs2<I: Iterator>
3946where
3947 I::Item: Clone,
3948{
3949 next: Option<(I::Item, I::Item)>,
3950 ps: ExhaustiveOrderedUniqueCollections<I, Vec<I::Item>>,
3951}
3952
3953impl<I: Iterator> Iterator for ExhaustiveUniqueVecs2<I>
3954where
3955 I::Item: Clone,
3956{
3957 type Item = Vec<I::Item>;
3958
3959 fn next(&mut self) -> Option<Vec<I::Item>> {
3960 if self.next.is_some() {
3961 let (a, b) = take(&mut self.next).unwrap();
3962 Some(vec![a, b])
3963 } else if let Some(p) = self.ps.next() {
3964 self.next = Some((p[1].clone(), p[0].clone()));
3965 Some(p)
3966 } else {
3967 None
3968 }
3969 }
3970}
3971
3972fn exhaustive_unique_vecs_2<I: Iterator>(xs: I) -> ExhaustiveUniqueVecs2<I>
3973where
3974 I::Item: Clone,
3975{
3976 ExhaustiveUniqueVecs2 {
3977 next: None,
3978 ps: exhaustive_ordered_unique_vecs_fixed_length(2, xs),
3979 }
3980}
3981
3982#[doc(hidden)]
3983#[derive(Clone, Debug)]
3984pub struct ExhaustiveUniqueVecsGenerator<T: Clone, I: Iterator<Item = T>> {
3985 phantom: PhantomData<(T, I)>,
3986}
3987
3988impl<T: Clone, I: Iterator<Item = T>> ExhaustiveUniqueVecsGenerator<T, I> {
3989 #[doc(hidden)]
3990 #[inline]
3991 pub const fn new() -> Self {
3992 Self {
3993 phantom: PhantomData,
3994 }
3995 }
3996}
3997
3998impl<T: Clone, I: Iterator<Item = T>>
3999 ExhaustiveDependentPairsYsGenerator<Vec<T>, Vec<T>, ExhaustiveVecPermutations<T>>
4000 for ExhaustiveUniqueVecsGenerator<T, I>
4001{
4002 #[inline]
4003 fn get_ys(&self, xs: &Vec<T>) -> ExhaustiveVecPermutations<T> {
4004 exhaustive_vec_permutations(xs.clone())
4005 }
4006}
4007
4008/// Generates all fixed-length [`Vec`]s of elements from an iterator, where the [`Vec`]s have no
4009/// repetitions and are ordered the same way as in the iterator.
4010#[derive(Clone)]
4011pub enum ExhaustiveUniqueVecsFixedLength<I: Iterator>
4012where
4013 I::Item: Clone,
4014{
4015 Zero(bool),
4016 One(I),
4017 Two(ExhaustiveUniqueVecs2<I>),
4018 GreaterThanTwo(
4019 ExhaustiveDependentPairs<
4020 Vec<I::Item>,
4021 Vec<I::Item>,
4022 RulerSequence<usize>,
4023 ExhaustiveUniqueVecsGenerator<I::Item, I>,
4024 ExhaustiveOrderedUniqueCollections<I, Vec<I::Item>>,
4025 ExhaustiveVecPermutations<I::Item>,
4026 >,
4027 ),
4028}
4029
4030impl<I: Iterator> Iterator for ExhaustiveUniqueVecsFixedLength<I>
4031where
4032 I::Item: Clone,
4033{
4034 type Item = Vec<I::Item>;
4035
4036 fn next(&mut self) -> Option<Vec<I::Item>> {
4037 match self {
4038 Self::Zero(done) => {
4039 if *done {
4040 None
4041 } else {
4042 *done = true;
4043 Some(Vec::new())
4044 }
4045 }
4046 Self::One(xs) => xs.next().map(|x| vec![x]),
4047 Self::Two(ps) => ps.next(),
4048 Self::GreaterThanTwo(xss) => xss.next().map(|p| p.1),
4049 }
4050 }
4051}
4052
4053/// Generates [`Vec`]s of a given length with elements from a single iterator, such that each
4054/// [`Vec`] has no repeated elements.
4055///
4056/// The source iterator should not repeat any elements, but this is not enforced.
4057///
4058/// If $k$ is 0, the output length is 1.
4059///
4060/// If $k$ is nonzero and the input iterator is infinite, the output length is also infinite.
4061///
4062/// If $k$ is nonzero and the input iterator length is $n$, the output length is
4063/// $$
4064/// (n)_ k = \prod_ {i=0}^{k-1}(n - i) = frac{n!}{(n-k)!}.
4065/// $$
4066///
4067/// If $k$ is 0, the output consists of one empty [`Vec`].
4068///
4069/// If `xs` is empty, the output is also empty, unless $k$ is 0.
4070///
4071/// # Examples
4072/// ```
4073/// use itertools::Itertools;
4074/// use malachite_base::vecs::exhaustive::exhaustive_unique_vecs_fixed_length;
4075///
4076/// let xss = exhaustive_unique_vecs_fixed_length(4, 1..=6)
4077/// .take(20)
4078/// .collect_vec();
4079/// assert_eq!(
4080/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
4081/// &[
4082/// &[1, 2, 3, 4],
4083/// &[1, 2, 3, 5],
4084/// &[1, 2, 4, 3],
4085/// &[1, 2, 4, 5],
4086/// &[1, 3, 2, 4],
4087/// &[1, 2, 5, 3],
4088/// &[1, 3, 4, 2],
4089/// &[1, 3, 4, 5],
4090/// &[1, 4, 2, 3],
4091/// &[1, 3, 2, 5],
4092/// &[1, 4, 3, 2],
4093/// &[1, 2, 5, 4],
4094/// &[2, 1, 3, 4],
4095/// &[1, 3, 5, 2],
4096/// &[2, 1, 4, 3],
4097/// &[2, 3, 4, 5],
4098/// &[2, 3, 1, 4],
4099/// &[1, 5, 2, 3],
4100/// &[2, 3, 4, 1],
4101/// &[1, 4, 2, 5]
4102/// ]
4103/// );
4104/// ```
4105pub fn exhaustive_unique_vecs_fixed_length<I: Iterator>(
4106 k: u64,
4107 xs: I,
4108) -> ExhaustiveUniqueVecsFixedLength<I>
4109where
4110 I::Item: Clone,
4111{
4112 match k {
4113 0 => ExhaustiveUniqueVecsFixedLength::Zero(false),
4114 1 => ExhaustiveUniqueVecsFixedLength::One(xs),
4115 2 => ExhaustiveUniqueVecsFixedLength::Two(exhaustive_unique_vecs_2(xs)),
4116 k => ExhaustiveUniqueVecsFixedLength::GreaterThanTwo(exhaustive_dependent_pairs(
4117 ruler_sequence(),
4118 exhaustive_ordered_unique_vecs_fixed_length(k, xs),
4119 ExhaustiveUniqueVecsGenerator::new(),
4120 )),
4121 }
4122}
4123
4124/// Generates all [`Vec`]s of elements from an iterator, where the [`Vec`]s have no repetitions and
4125/// are ordered the same way as in the iterator.
4126#[derive(Clone)]
4127pub struct ExhaustiveUniqueVecs<I: Iterator>
4128where
4129 I::Item: Clone,
4130{
4131 xs: ExhaustiveDependentPairs<
4132 Vec<I::Item>,
4133 Vec<I::Item>,
4134 RulerSequence<usize>,
4135 ExhaustiveUniqueVecsGenerator<I::Item, I>,
4136 ExhaustiveOrderedUniqueCollections<I, Vec<I::Item>>,
4137 ExhaustiveVecPermutations<I::Item>,
4138 >,
4139}
4140
4141impl<I: Iterator> Iterator for ExhaustiveUniqueVecs<I>
4142where
4143 I::Item: Clone,
4144{
4145 type Item = Vec<I::Item>;
4146
4147 #[inline]
4148 fn next(&mut self) -> Option<Vec<I::Item>> {
4149 self.xs.next().map(|p| p.1)
4150 }
4151}
4152
4153/// Generates [`Vec`]s with elements from a single iterator, such that each [`Vec`] has no repeated
4154/// elements.
4155///
4156/// The source iterator should not repeat any elements, but this is not enforced.
4157///
4158/// If the input iterator is infinite, the output length is also infinite.
4159///
4160/// If the input iterator length is $n$, the output length is
4161/// $$
4162/// \sum_ {k=0}^n \frac{n!}{k!}
4163/// $$
4164/// $$
4165/// = \\begin{cases}
4166/// 1 & \text{if} \\quad n = 0, \\\\
4167/// 2 & \text{if} \\quad n = 1, \\\\
4168/// \operatorname{round}(en!) & \\text{otherwise}.
4169/// \\end{cases}
4170/// $$
4171///
4172/// See <https://oeis.org/A000522>.
4173///
4174/// If `xs` is empty, the output consists of a single empty [`Vec`].
4175///
4176/// # Examples
4177/// ```
4178/// use itertools::Itertools;
4179/// use malachite_base::vecs::exhaustive::exhaustive_unique_vecs;
4180///
4181/// let xss = exhaustive_unique_vecs(1..=4).take(20).collect_vec();
4182/// assert_eq!(
4183/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
4184/// &[
4185/// &[][..],
4186/// &[1],
4187/// &[2],
4188/// &[3],
4189/// &[1, 2],
4190/// &[1, 3],
4191/// &[2, 1],
4192/// &[1, 2, 3],
4193/// &[3, 1],
4194/// &[2, 3],
4195/// &[3, 2],
4196/// &[4],
4197/// &[1, 3, 2],
4198/// &[1, 4],
4199/// &[2, 1, 3],
4200/// &[3, 4],
4201/// &[2, 3, 1],
4202/// &[4, 1],
4203/// &[3, 1, 2],
4204/// &[2, 4]
4205/// ]
4206/// );
4207/// ```
4208#[inline]
4209pub fn exhaustive_unique_vecs<I: Iterator>(xs: I) -> ExhaustiveUniqueVecs<I>
4210where
4211 I::Item: Clone,
4212{
4213 ExhaustiveUniqueVecs {
4214 xs: exhaustive_dependent_pairs(
4215 ruler_sequence(),
4216 exhaustive_ordered_unique_vecs(xs),
4217 ExhaustiveUniqueVecsGenerator::new(),
4218 ),
4219 }
4220}
4221
4222/// Generates [`Vec`]s with a mininum length, with elements from a single iterator, such that each
4223/// [`Vec`] has no repeated elements.
4224///
4225/// The source iterator should not repeat any elements, but this is not enforced.
4226///
4227/// If the input iterator is infinite, the output length is also infinite.
4228///
4229/// If the input iterator length is $n$ and the `min_length` is $\ell$, the output length is
4230/// $$
4231/// \sum_ {k=\ell}^n \frac{n!}{k!}.
4232/// $$
4233///
4234/// # Examples
4235/// ```
4236/// use itertools::Itertools;
4237/// use malachite_base::vecs::exhaustive::exhaustive_unique_vecs_min_length;
4238///
4239/// let xss = exhaustive_unique_vecs_min_length(2, 1..=4)
4240/// .take(20)
4241/// .collect_vec();
4242/// assert_eq!(
4243/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
4244/// &[
4245/// &[1, 2][..],
4246/// &[1, 3],
4247/// &[2, 1],
4248/// &[2, 3],
4249/// &[3, 1],
4250/// &[3, 2],
4251/// &[1, 2, 3],
4252/// &[1, 2, 4],
4253/// &[1, 3, 2],
4254/// &[1, 4],
4255/// &[2, 1, 3],
4256/// &[2, 4],
4257/// &[2, 3, 1],
4258/// &[4, 1],
4259/// &[3, 1, 2],
4260/// &[3, 4],
4261/// &[3, 2, 1],
4262/// &[4, 2],
4263/// &[1, 4, 2],
4264/// &[1, 3, 4]
4265/// ]
4266/// );
4267/// ```
4268#[inline]
4269pub fn exhaustive_unique_vecs_min_length<I: Iterator>(
4270 min_length: u64,
4271 xs: I,
4272) -> ExhaustiveUniqueVecs<I>
4273where
4274 I::Item: Clone,
4275{
4276 ExhaustiveUniqueVecs {
4277 xs: exhaustive_dependent_pairs(
4278 ruler_sequence(),
4279 exhaustive_ordered_unique_vecs_min_length(min_length, xs),
4280 ExhaustiveUniqueVecsGenerator::new(),
4281 ),
4282 }
4283}
4284
4285/// Generates [`Vec`]s, with lengths in a range $[a, b)$, with elements from a single iterator, such
4286/// that each [`Vec`] has no repeated elements.
4287///
4288/// The source iterator should not repeat any elements, but this is not enforced.
4289///
4290/// If $a \leq b$, the output is empty.
4291///
4292/// If $a = 0$ and $b = 1$, the output consists of a single empty [`Vec`].
4293///
4294/// If the input iterator is infinite and $0 < a < b$, the output length is also infinite.
4295///
4296/// If the input iterator length is $n$, the output length is
4297/// $$
4298/// \sum_{i=a}^{b - 1} \frac{n!}{k!}.
4299/// $$
4300///
4301/// # Examples
4302/// ```
4303/// use itertools::Itertools;
4304/// use malachite_base::vecs::exhaustive::exhaustive_unique_vecs_length_range;
4305///
4306/// let xss = exhaustive_unique_vecs_length_range(2, 4, 1..=4)
4307/// .take(20)
4308/// .collect_vec();
4309/// assert_eq!(
4310/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
4311/// &[
4312/// &[1, 2][..],
4313/// &[1, 3],
4314/// &[2, 1],
4315/// &[2, 3],
4316/// &[3, 1],
4317/// &[3, 2],
4318/// &[1, 2, 3],
4319/// &[1, 2, 4],
4320/// &[1, 3, 2],
4321/// &[1, 4],
4322/// &[2, 1, 3],
4323/// &[2, 4],
4324/// &[2, 3, 1],
4325/// &[4, 1],
4326/// &[3, 1, 2],
4327/// &[3, 4],
4328/// &[3, 2, 1],
4329/// &[4, 2],
4330/// &[1, 4, 2],
4331/// &[1, 3, 4]
4332/// ]
4333/// );
4334/// ```
4335#[inline]
4336pub fn exhaustive_unique_vecs_length_range<I: Iterator>(
4337 a: u64,
4338 b: u64,
4339 xs: I,
4340) -> ExhaustiveUniqueVecs<I>
4341where
4342 I::Item: Clone,
4343{
4344 ExhaustiveUniqueVecs {
4345 xs: exhaustive_dependent_pairs(
4346 ruler_sequence(),
4347 exhaustive_ordered_unique_vecs_length_range(a, b, xs),
4348 ExhaustiveUniqueVecsGenerator::new(),
4349 ),
4350 }
4351}
4352
4353/// Generates [`Vec`]s, with lengths in a range $[a, b]$, with elements from a single iterator, such
4354/// that each [`Vec`] has no repeated elements.
4355///
4356/// The source iterator should not repeat any elements, but this is not enforced.
4357///
4358/// If $a < b$, the output is empty.
4359///
4360/// If $a = b = 0$, the output consists of a single empty [`Vec`].
4361///
4362/// If the input iterator is infinite and $0 < a \leq b$, the output length is also infinite.
4363///
4364/// If the input iterator length is $n$, the output length is
4365/// $$
4366/// \sum_{i=a}^b \frac{n!}{k!}.
4367/// $$
4368///
4369/// # Examples
4370/// ```
4371/// use itertools::Itertools;
4372/// use malachite_base::vecs::exhaustive::exhaustive_unique_vecs_length_inclusive_range;
4373///
4374/// let xss = exhaustive_unique_vecs_length_inclusive_range(2, 3, 1..=4)
4375/// .take(20)
4376/// .collect_vec();
4377/// assert_eq!(
4378/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
4379/// &[
4380/// &[1, 2][..],
4381/// &[1, 3],
4382/// &[2, 1],
4383/// &[2, 3],
4384/// &[3, 1],
4385/// &[3, 2],
4386/// &[1, 2, 3],
4387/// &[1, 2, 4],
4388/// &[1, 3, 2],
4389/// &[1, 4],
4390/// &[2, 1, 3],
4391/// &[2, 4],
4392/// &[2, 3, 1],
4393/// &[4, 1],
4394/// &[3, 1, 2],
4395/// &[3, 4],
4396/// &[3, 2, 1],
4397/// &[4, 2],
4398/// &[1, 4, 2],
4399/// &[1, 3, 4]
4400/// ]
4401/// );
4402/// ```
4403#[inline]
4404pub fn exhaustive_unique_vecs_length_inclusive_range<I: Iterator>(
4405 a: u64,
4406 b: u64,
4407 xs: I,
4408) -> ExhaustiveUniqueVecs<I>
4409where
4410 I::Item: Clone,
4411{
4412 ExhaustiveUniqueVecs {
4413 xs: exhaustive_dependent_pairs(
4414 ruler_sequence(),
4415 exhaustive_ordered_unique_vecs_length_inclusive_range(a, b, xs),
4416 ExhaustiveUniqueVecsGenerator::new(),
4417 ),
4418 }
4419}
4420
4421/// Generates all $k$-compositions of a number: all length-$k$ [`Vec`]s of positive [`usize`]s whose
4422/// sum is a given number.
4423#[derive(Clone, Debug)]
4424pub struct LexKCompositions {
4425 done: bool,
4426 first: bool,
4427 xs: Vec<usize>,
4428}
4429
4430impl Iterator for LexKCompositions {
4431 type Item = Vec<usize>;
4432
4433 fn next(&mut self) -> Option<Vec<usize>> {
4434 if self.done {
4435 return None;
4436 } else if self.first {
4437 self.first = false;
4438 return Some(self.xs.clone());
4439 }
4440 let last_not_one_index = self.xs.iter().rposition(|&x| x != 1);
4441 if last_not_one_index.is_none() || last_not_one_index == Some(0) {
4442 self.done = true;
4443 return None;
4444 }
4445 let last_not_one_index = last_not_one_index.unwrap();
4446 self.xs[last_not_one_index - 1] += 1;
4447 let last_not_one = self.xs[last_not_one_index];
4448 let (last, init) = self.xs.split_last_mut().unwrap();
4449 *last = last_not_one - 1;
4450 for x in &mut init[last_not_one_index..] {
4451 *x = 1;
4452 }
4453 Some(self.xs.clone())
4454 }
4455}
4456
4457/// Generates all $k$-compositions of a number: given $n$ and $k$, generates all length-$k$ [`Vec`]s
4458/// of positive [`usize`]s whose sum is $n$.
4459///
4460/// The [`Vec`]s are output in lexicographic order.
4461///
4462/// If $k = 0$ and $n \neq 0$, or if $n < k$, then the output is empty.
4463///
4464/// The output length is
4465/// $$
4466/// \binom{n-1}{k-1}.
4467/// $$
4468///
4469/// # Examples
4470/// ```
4471/// use itertools::Itertools;
4472/// use malachite_base::vecs::exhaustive::lex_k_compositions;
4473///
4474/// let xss = lex_k_compositions(5, 3).collect_vec();
4475/// assert_eq!(
4476/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
4477/// &[&[1, 1, 3], &[1, 2, 2], &[1, 3, 1], &[2, 1, 2], &[2, 2, 1], &[3, 1, 1]]
4478/// );
4479/// ```
4480pub fn lex_k_compositions(n: usize, k: usize) -> LexKCompositions {
4481 if k == 0 && n != 0 || n < k {
4482 return LexKCompositions {
4483 done: true,
4484 first: true,
4485 xs: Vec::new(),
4486 };
4487 }
4488 let mut xs = vec![1; k];
4489 if k != 0 {
4490 xs[k - 1] = n + 1 - k;
4491 }
4492 LexKCompositions {
4493 done: false,
4494 first: true,
4495 xs,
4496 }
4497}
4498
4499#[doc(hidden)]
4500#[derive(Clone, Debug)]
4501pub struct LexKCompositionsGenerator {
4502 k: usize,
4503}
4504
4505impl ExhaustiveDependentPairsYsGenerator<usize, Vec<usize>, LexKCompositions>
4506 for LexKCompositionsGenerator
4507{
4508 #[inline]
4509 fn get_ys(&self, &n: &usize) -> LexKCompositions {
4510 lex_k_compositions(n, self.k)
4511 }
4512}
4513
4514/// Generates $k$-compositions of $n$ for all $n$ in a given range: all length-$k$ [`Vec`]s of
4515/// positive [`usize`]s whose sum is in a given range.
4516#[derive(Clone, Debug)]
4517pub struct ExhaustiveCombinedKCompositions {
4518 xs: ExhaustiveDependentPairs<
4519 usize,
4520 Vec<usize>,
4521 RulerSequence<usize>,
4522 LexKCompositionsGenerator,
4523 PrimitiveIntIncreasingRange<usize>,
4524 LexKCompositions,
4525 >,
4526}
4527
4528impl Iterator for ExhaustiveCombinedKCompositions {
4529 type Item = Vec<usize>;
4530
4531 #[inline]
4532 fn next(&mut self) -> Option<Vec<usize>> {
4533 self.xs.next().map(|p| p.1)
4534 }
4535}
4536
4537/// Given $n_\text{min}$, $n_\text{max}$, and $k$, generates all length-$k$ [`Vec`]s of positive
4538/// [`usize`]s whose sum is in the closed interval $[n_\text{min}, n_\text{max}]$.
4539///
4540/// The output length is
4541/// $$
4542/// \sum_{n=n_\text{min}}^{n_\text{max}} \binom{n-1}{k-1}.
4543/// $$
4544///
4545/// # Panics
4546/// Panics if $n_\text{min} > n_\text{max}$.
4547///
4548/// # Examples
4549/// ```
4550/// use itertools::Itertools;
4551/// use malachite_base::vecs::exhaustive::exhaustive_combined_k_compositions;
4552///
4553/// let xss = exhaustive_combined_k_compositions(4, 6, 3).collect_vec();
4554/// assert_eq!(
4555/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
4556/// &[
4557/// &[1, 1, 2],
4558/// &[1, 1, 3],
4559/// &[1, 2, 1],
4560/// &[1, 1, 4],
4561/// &[2, 1, 1],
4562/// &[1, 2, 2],
4563/// &[1, 3, 1],
4564/// &[1, 2, 3],
4565/// &[2, 1, 2],
4566/// &[1, 3, 2],
4567/// &[2, 2, 1],
4568/// &[3, 1, 1],
4569/// &[1, 4, 1],
4570/// &[2, 1, 3],
4571/// &[2, 2, 2],
4572/// &[2, 3, 1],
4573/// &[3, 1, 2],
4574/// &[3, 2, 1],
4575/// &[4, 1, 1]
4576/// ]
4577/// );
4578/// ```
4579#[inline]
4580pub fn exhaustive_combined_k_compositions(
4581 n_min: usize,
4582 n_max: usize,
4583 k: usize,
4584) -> ExhaustiveCombinedKCompositions {
4585 ExhaustiveCombinedKCompositions {
4586 xs: exhaustive_dependent_pairs(
4587 ruler_sequence(),
4588 primitive_int_increasing_inclusive_range(n_min, n_max),
4589 LexKCompositionsGenerator { k },
4590 ),
4591 }
4592}