malachite_base/tuples/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, WrappingFrom};
13use crate::num::logic::traits::SignificantBits;
14use crate::vecs::exhaustive::{
15 UniqueIndices, fixed_length_ordered_unique_indices_helper, next_bit_pattern, unique_indices,
16};
17use alloc::vec;
18use alloc::vec::Vec;
19use core::cmp::max;
20use core::fmt::Debug;
21use core::iter::{Once, once};
22use core::marker::PhantomData;
23use core::mem::take;
24
25/// Generates the only unit: `()`.
26///
27/// The output length is 1.
28///
29/// # Worst-case complexity per iteration
30/// Constant time and additional memory.
31///
32/// # Examples
33/// ```
34/// use itertools::Itertools;
35/// use malachite_base::tuples::exhaustive::exhaustive_units;
36///
37/// assert_eq!(exhaustive_units().collect_vec(), &[()]);
38/// ```
39pub fn exhaustive_units() -> Once<()> {
40 once(())
41}
42
43// hack for macro
44pub_test! {
45#[inline]
46clone_helper<T: Clone>(x: &T, _i: usize) -> T {
47 x.clone()
48}}
49
50/// Defines lexicographic tuple generators.
51///
52/// Malachite provides [`lex_pairs`] and [`lex_pairs_from_single`], but you can also define
53/// `lex_triples`, `lex_quadruples`, and so on, and `lex_triples_from_single`,
54/// `lex_quadruples_from_single`, and so on, in your program using the code below. The documentation
55/// for [`lex_pairs`] and [`lex_pairs_from_single`] describes these other functions as well.
56///
57/// See usage examples [here](self#lex_pairs) and [here](self#lex_pairs_from_single).
58///
59/// ```
60/// use malachite_base::iterators::iterator_cache::IteratorCache;
61/// use malachite_base::lex_tuples;
62///
63/// fn clone_helper<T: Clone>(x: &T, _i: usize) -> T {
64/// x.clone()
65/// }
66///
67/// lex_tuples!(
68/// (pub(crate)),
69/// 3,
70/// LexTriples,
71/// LexTriplesFromSingle,
72/// lex_triples,
73/// lex_triples_from_single,
74/// (T, T, T),
75/// [0, X, I, xs, x],
76/// [1, Y, J, ys, y],
77/// [2, Z, K, zs, z]
78/// );
79/// lex_tuples!(
80/// (pub(crate)),
81/// 4,
82/// LexQuadruples,
83/// LexQuadruplesFromSingle,
84/// lex_quadruples,
85/// lex_quadruples_from_single,
86/// (T, T, T, T),
87/// [0, X, I, xs, x],
88/// [1, Y, J, ys, y],
89/// [2, Z, K, zs, z],
90/// [3, W, L, ws, w]
91/// );
92/// lex_tuples!(
93/// (pub(crate)),
94/// 5,
95/// LexQuintuples,
96/// LexQuintuplesFromSingle,
97/// lex_quintuples,
98/// lex_quintuples_from_single,
99/// (T, T, T, T, T),
100/// [0, X, I, xs, x],
101/// [1, Y, J, ys, y],
102/// [2, Z, K, zs, z],
103/// [3, W, L, ws, w],
104/// [4, V, M, vs, v]
105/// );
106/// lex_tuples!(
107/// (pub(crate)),
108/// 6,
109/// LexSextuples,
110/// LexSextuplesFromSingle,
111/// lex_sextuples,
112/// lex_sextuples_from_single,
113/// (T, T, T, T, T, T),
114/// [0, X, I, xs, x],
115/// [1, Y, J, ys, y],
116/// [2, Z, K, zs, z],
117/// [3, W, L, ws, w],
118/// [4, V, M, vs, v],
119/// [5, U, N, us, u]
120/// );
121/// lex_tuples!(
122/// (pub(crate)),
123/// 7,
124/// LexSeptuples,
125/// LexSeptuplesFromSingle,
126/// lex_septuples,
127/// lex_septuples_from_single,
128/// (T, T, T, T, T, T, T),
129/// [0, X, I, xs, x],
130/// [1, Y, J, ys, y],
131/// [2, Z, K, zs, z],
132/// [3, W, L, ws, w],
133/// [4, V, M, vs, v],
134/// [5, U, N, us, u],
135/// [6, T, O, ts, t]
136/// );
137/// lex_tuples!(
138/// (pub(crate)),
139/// 8,
140/// LexOctuples,
141/// LexOctuplesFromSingle,
142/// lex_octuples,
143/// lex_octuples_from_single,
144/// (T, T, T, T, T, T, T, T),
145/// [0, X, I, xs, x],
146/// [1, Y, J, ys, y],
147/// [2, Z, K, zs, z],
148/// [3, W, L, ws, w],
149/// [4, V, M, vs, v],
150/// [5, U, N, us, u],
151/// [6, T, O, ts, t],
152/// [7, S, P, ss, s]
153/// );
154/// ```
155#[macro_export]
156macro_rules! lex_tuples {
157 (
158 ($($vis:tt)*),
159 $k: expr,
160 $exhaustive_struct: ident,
161 $exhaustive_struct_from_single: ident,
162 $exhaustive_fn: ident,
163 $exhaustive_fn_from_single: ident,
164 $single_out: tt,
165 $([$i: expr, $t: ident, $it: ident, $xs: ident, $x:ident]),*
166 ) => {
167 /// This documentation applies not only to `LexPairs`, but also to `LexTriples`,
168 /// `LexQuadruples`, and so on. See `lex_tuples` for more information.
169 ///
170 /// Generates all $n$-tuples with elements from $n$ iterators, in lexicographic order.
171 ///
172 /// The order is lexicographic with respect to the order of the element iterators.
173 #[derive(Clone, Debug)]
174 $($vis)* struct $exhaustive_struct<$($t: Clone, $it: Iterator<Item = $t>,)*> {
175 first: bool,
176 done: bool,
177 $($xs: IteratorCache<$it>,)*
178 counters: [usize; $k],
179 }
180
181 impl<$($t: Clone, $it: Iterator<Item = $t>,)*> $exhaustive_struct<$($t, $it,)*> {
182 fn increment_counters(&mut self) -> bool {
183 for (i, counter) in self.counters.iter_mut().enumerate().rev() {
184 *counter += 1;
185 let no_carry = match i {
186 $(
187 $i => self.$xs.get(*counter).is_some(),
188 )*
189 _ => unreachable!(),
190 };
191 if no_carry {
192 return false;
193 } else if i == 0 {
194 return true;
195 }
196 *counter = 0;
197 }
198 false
199 }
200 }
201
202 impl<$($t: Clone, $it: Iterator<Item = $t>,)*> Iterator for $exhaustive_struct<$($t, $it,)*>
203 {
204 type Item = ($($t,)*);
205
206 fn next(&mut self) -> Option<Self::Item> {
207 if self.done {
208 None
209 } else if self.first {
210 self.first = false;
211 $(
212 let $x;
213 )*
214 $(
215 if let Some(x) = self.$xs.get(0) {
216 $x = x.clone();
217 } else {
218 self.done = true;
219 return None;
220 }
221 )*
222 Some(($($x,)*))
223 } else if self.increment_counters() {
224 self.done = true;
225 None
226 } else {
227 Some(($(self.$xs.get(self.counters[$i]).unwrap().clone(),)*))
228 }
229 }
230 }
231
232 /// This documentation applies not only to `lex_pairs`, but also to `lex_triples`,
233 /// `lex_quadruples`, and so on. See [`lex_tuples`] for more information.
234 ///
235 /// Generates all $n$-tuples with elements from $n$ iterators, in lexicographic order.
236 ///
237 /// The order is lexicographic with respect to the order of the element iterators.
238 ///
239 /// All of `ys`, `zs`, ... (but not necessarily `xs`) must be finite. If `xs` is finite, the
240 /// output length is the product of the lengths of all the input iterators. If `xs` is
241 /// infinite, the output is also infinite.
242 ///
243 /// If any of `xs`, `ys`, `zs`, ... is empty, the output is also empty.
244 ///
245 /// # Examples
246 /// See [here](self#lex_pairs).
247 #[allow(dead_code)]
248 $($vis)* const fn $exhaustive_fn<$($t: Clone, $it: Iterator<Item = $t>,)*>(
249 $($xs: $it,)*
250 ) -> $exhaustive_struct<$($t, $it,)*> {
251 $exhaustive_struct {
252 first: true,
253 done: false,
254 $($xs: IteratorCache::new($xs),)*
255 counters: [$($i * 0,)*],
256 }
257 }
258
259 /// This documentation applies not only to `LexPairsFromSingle`, but also to
260 /// `LexTriplesFromSingle`, `LexQuadruplesFromSingle`, and so on. See [`lex_tuples`] for
261 /// more information.
262 ///
263 /// Generates all $n$-tuples with elements a single iterator, in lexicographic order.
264 ///
265 /// The order is lexicographic with respect to the order of the element iterator.
266 #[derive(Clone, Debug)]
267 $($vis)* struct $exhaustive_struct_from_single<T: Clone, I: Iterator<Item = T>> {
268 first: bool,
269 done: bool,
270 xs: IteratorCache<I>,
271 counters: [usize; $k],
272 }
273
274 impl<T: Clone, I: Iterator<Item = T>> $exhaustive_struct_from_single<T, I> {
275 fn increment_counters(&mut self) -> bool {
276 for (i, counter) in self.counters.iter_mut().enumerate().rev() {
277 *counter += 1;
278 if self.xs.get(*counter).is_some() {
279 return false;
280 } else if i == 0 {
281 return true;
282 }
283 *counter = 0;
284 }
285 false
286 }
287 }
288
289 impl<T: Clone, I: Iterator<Item = T>> Iterator for $exhaustive_struct_from_single<T, I> {
290 type Item = $single_out;
291
292 fn next(&mut self) -> Option<$single_out> {
293 if self.done {
294 None
295 } else if self.first {
296 self.first = false;
297 if let Some(x) = self.xs.get(0) {
298 Some(($(clone_helper(x, $i),)*))
299 } else {
300 self.done = true;
301 None
302 }
303 } else if self.increment_counters() {
304 self.done = true;
305 None
306 } else {
307 Some(($(self.xs.get(self.counters[$i]).unwrap().clone(),)*))
308 }
309 }
310 }
311
312 /// This documentation applies not only to `lex_pairs_from_single`, but also to
313 /// `lex_triples_from_single`, `lex_quadruples_from_single`, and so on. See [`lex_tuples`]
314 /// for more information.
315 ///
316 /// Generates all $n$-tuples with elements from a single iterator, in lexicographic order.
317 ///
318 /// The order is lexicographic with respect to the order of the element iterator.
319 ///
320 /// `xs` must be finite.
321 ///
322 /// The output length is $k^n$, where $k$ is `xs.count()` and $n$ is `len`.
323 ///
324 /// If `xs` is empty, the output is also empty.
325 ///
326 /// # Examples
327 /// See [here](self#lex_pairs_from_single).
328 #[allow(dead_code)]
329 $($vis)* const fn $exhaustive_fn_from_single<T: Clone, I: Iterator<Item = T>>(
330 xs: I
331 ) -> $exhaustive_struct_from_single<T, I> {
332 $exhaustive_struct_from_single {
333 first: true,
334 done: false,
335 xs: IteratorCache::new(xs),
336 counters: [$($i * 0,)*],
337 }
338 }
339 }
340}
341lex_tuples!(
342 (pub),
343 2,
344 LexPairs,
345 LexPairsFromSingle,
346 lex_pairs,
347 lex_pairs_from_single,
348 (T, T),
349 [0, X, I, xs, x],
350 [1, Y, J, ys, y]
351);
352lex_tuples!(
353 (pub(crate)),
354 4,
355 LexQuadruples,
356 LexQuadruplesFromSingle,
357 lex_quadruples,
358 lex_quadruples_from_single,
359 (T, T, T, T),
360 [0, X, I, xs, x],
361 [1, Y, J, ys, y],
362 [2, Z, K, zs, z],
363 [3, W, L, ws, w]
364);
365
366/// Defines custom lexicographic tuple generators.
367///
368/// You can define custom tuple generators like `lex_triples_xxy` in your program using the code
369/// below.
370///
371/// See usage examples [here](self#lex_triples_xxy).
372///
373/// ```
374/// use malachite_base::iterators::iterator_cache::IteratorCache;
375/// use malachite_base::lex_custom_tuples;
376///
377/// fn unwrap_triple<X, Y, Z>((a, b, c): (Option<X>, Option<Y>, Option<Z>)) -> (X, Y, Z) {
378/// (a.unwrap(), b.unwrap(), c.unwrap())
379/// }
380///
381/// lex_custom_tuples! {
382/// (pub),
383/// LexTriplesXXY,
384/// (X, X, Y),
385/// (None, None, None),
386/// unwrap_triple,
387/// lex_triples_xxy,
388/// [X, I, xs, [0, x_0], [1, x_1]],
389/// [Y, J, ys, [2, y_2]]
390/// }
391/// lex_custom_tuples!(
392/// (pub),
393/// LexTriplesXYX,
394/// (X, Y, X),
395/// (None, None, None),
396/// unwrap_triple,
397/// lex_triples_xyx,
398/// [X, I, xs, [0, x_0], [2, x_2]],
399/// [Y, J, ys, [1, y_1]]
400/// );
401/// lex_custom_tuples!(
402/// (pub),
403/// LexTriplesXYY,
404/// (X, Y, Y),
405/// (None, None, None),
406/// unwrap_triple,
407/// lex_triples_xyy,
408/// [X, I, xs, [0, x_0]],
409/// [Y, J, ys, [1, y_1], [2, y_2]]
410/// );
411/// ```
412#[macro_export]
413macro_rules! lex_custom_tuples {
414 (
415 ($($vis:tt)*),
416 $exhaustive_struct: ident,
417 $out_t: ty,
418 $nones: expr,
419 $unwrap_tuple: ident,
420 $exhaustive_fn: ident,
421 $([$t: ident, $it: ident, $xs: ident, $([$i: tt, $x: ident]),*]),*
422 ) => {
423 // Generates all $n$-tuples with elements from $m$ iterators, where $m \leq n$, in
424 // lexicographic order.
425 //
426 // The order is lexicographic with respect to the order of the element iterators.
427 //
428 // The mapping from iterators to tuple slots is indicated by the struct name; for example,
429 // in `LexTriplesXYX` there are two iterators, `X`, and `Y`; `X` generates the elements in
430 // the first and third slots of the output triples, and `Y` generates the elements in the
431 // second slots.
432 #[derive(Clone, Debug)]
433 $($vis)* struct $exhaustive_struct<$($t: Clone, $it: Iterator<Item = $t>,)*> {
434 first: bool,
435 done: bool,
436 $($xs: IteratorCache<$it>,)*
437 counters: Vec<usize>,
438 }
439
440 impl<$($t: Clone, $it: Iterator<Item = $t>,)*> $exhaustive_struct<$($t, $it,)*> {
441 fn increment_counters(&mut self) -> bool {
442 for (i, counter) in self.counters.iter_mut().enumerate().rev() {
443 *counter += 1;
444 let no_carry = match i {
445 $(
446 $($i)|* => self.$xs.get(*counter).is_some(),
447 )*
448 _ => unreachable!(),
449 };
450 if no_carry {
451 return false;
452 } else if i == 0 {
453 return true;
454 }
455 *counter = 0;
456 }
457 false
458 }
459 }
460
461 impl<$($t: Clone, $it: Iterator<Item = $t>,)*> Iterator for $exhaustive_struct<$($t, $it,)*>
462 {
463 type Item = $out_t;
464
465 fn next(&mut self) -> Option<Self::Item> {
466 if self.done {
467 None
468 } else if self.first {
469 self.first = false;
470 $($(let $x;)*)*
471 $(
472 if let Some(x) = self.$xs.get(0) {
473 $($x = x.clone();)*
474 } else {
475 self.done = true;
476 return None;
477 }
478 )*
479 let mut out = $nones;
480 $($(out.$i = Some($x);)*)*
481 Some($unwrap_tuple(out))
482 } else if self.increment_counters() {
483 self.done = true;
484 None
485 } else {
486 let mut out = $nones;
487 $($(out.$i = self.$xs.get(self.counters[$i]).cloned();)*)*
488 Some($unwrap_tuple(out))
489 }
490 }
491 }
492
493 // Generates all $n$-tuples with elements from $m$ iterators, where $m \leq n$, in
494 // lexicographic order.
495 //
496 // The order is lexicographic with respect to the order of the element iterators.
497 //
498 // The mapping from iterators to tuple slots is indicated by the function name; for example,
499 // `lex_triples_xyx` takes two iterators, `xs`, and `ys`; `xs` generates the elements in the
500 // first and third slots of the output triples, and `ys` generates the elements in the
501 // second slots.
502 //
503 // Let `xs` be the input iterator mapped to the first slot of the output tuples. All the
504 // input iterators, except possibly `xs`, must be finite. If `xs` is finite, the output
505 // length is the product of the lengths of all the input iterators. If `xs` is infinite, the
506 // output is also infinite.
507 //
508 // If any of the input iterators is empty, the output is also empty.
509 //
510 // # Examples
511 // See [here](self#lex_triples_xyx).
512 $($vis)* fn $exhaustive_fn<$($t: Clone, $it: Iterator<Item = $t>,)*>(
513 $($xs: $it,)*
514 ) -> $exhaustive_struct<$($t, $it,)*> {
515 $exhaustive_struct {
516 first: true,
517 done: false,
518 $($xs: IteratorCache::new($xs),)*
519 counters: vec![$($(($i * 0),)*)*],
520 }
521 }
522 }
523}
524
525/// Defines exhaustive tuple generators that generate tuples from a single iterator.
526///
527/// Malachite provides [`exhaustive_pairs_from_single`] and [`exhaustive_pairs_1_input`], but you
528/// can also define `exhaustive_triples_from_single`, `exhaustive_quadruples_from_single`, and so
529/// on, and `exhaustive_triples_1_input`, `exhaustive_quadruples_1_input`, and so on, in your
530/// program using the code below. The documentation for [`exhaustive_pairs_from_single`] and
531/// [`exhaustive_pairs_1_input`] describes these other functions as well.
532///
533/// See usage examples [here](self#exhaustive_pairs_from_single) and
534/// [here](self#exhaustive_pairs_1_input).
535///
536/// ```
537/// use malachite_base::exhaustive_tuples_1_input;
538/// use malachite_base::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
539/// use malachite_base::iterators::iterator_cache::IteratorCache;
540/// use malachite_base::num::arithmetic::traits::CheckedPow;
541/// use malachite_base::num::conversion::traits::{ExactFrom, WrappingFrom};
542/// use malachite_base::num::logic::traits::SignificantBits;
543/// use std::cmp::max;
544/// use std::marker::PhantomData;
545///
546/// exhaustive_tuples_1_input!(
547/// (pub(crate)),
548/// ExhaustiveTriples1Input,
549/// exhaustive_triples_1_input,
550/// exhaustive_triples_from_single,
551/// (I::Item, I::Item, I::Item),
552/// [0, output_type_x],
553/// [1, output_type_y],
554/// [2, output_type_z]
555/// );
556/// exhaustive_tuples_1_input!(
557/// (pub(crate)),
558/// ExhaustiveQuadruples1Input,
559/// exhaustive_quadruples_1_input,
560/// exhaustive_quadruples_from_single,
561/// (I::Item, I::Item, I::Item, I::Item),
562/// [0, output_type_x],
563/// [1, output_type_y],
564/// [2, output_type_z],
565/// [3, output_type_w]
566/// );
567/// exhaustive_tuples_1_input!(
568/// (pub(crate)),
569/// ExhaustiveQuintuples1Input,
570/// exhaustive_quintuples_1_input,
571/// exhaustive_quintuples_from_single,
572/// (I::Item, I::Item, I::Item, I::Item, I::Item),
573/// [0, output_type_x],
574/// [1, output_type_y],
575/// [2, output_type_z],
576/// [3, output_type_w],
577/// [4, output_type_v]
578/// );
579/// exhaustive_tuples_1_input!(
580/// (pub(crate)),
581/// ExhaustiveSextuples1Input,
582/// exhaustive_sextuples_1_input,
583/// exhaustive_sextuples_from_single,
584/// (I::Item, I::Item, I::Item, I::Item, I::Item, I::Item),
585/// [0, output_type_x],
586/// [1, output_type_y],
587/// [2, output_type_z],
588/// [3, output_type_w],
589/// [4, output_type_v],
590/// [5, output_type_u]
591/// );
592/// exhaustive_tuples_1_input!(
593/// (pub(crate)),
594/// ExhaustiveSeptuples1Input,
595/// exhaustive_septuples_1_input,
596/// exhaustive_septuples_from_single,
597/// (
598/// I::Item,
599/// I::Item,
600/// I::Item,
601/// I::Item,
602/// I::Item,
603/// I::Item,
604/// I::Item
605/// ),
606/// [0, output_type_x],
607/// [1, output_type_y],
608/// [2, output_type_z],
609/// [3, output_type_w],
610/// [4, output_type_v],
611/// [5, output_type_u],
612/// [6, output_type_t]
613/// );
614/// exhaustive_tuples_1_input!(
615/// (pub(crate)),
616/// ExhaustiveOctuples1Input,
617/// exhaustive_octuples_1_input,
618/// exhaustive_octuples_from_single,
619/// (
620/// I::Item,
621/// I::Item,
622/// I::Item,
623/// I::Item,
624/// I::Item,
625/// I::Item,
626/// I::Item,
627/// I::Item
628/// ),
629/// [0, output_type_x],
630/// [1, output_type_y],
631/// [2, output_type_z],
632/// [3, output_type_w],
633/// [4, output_type_v],
634/// [5, output_type_u],
635/// [6, output_type_t],
636/// [7, output_type_s]
637/// );
638/// ```
639#[macro_export]
640macro_rules! exhaustive_tuples_1_input {
641 (
642 ($($vis:tt)*),
643 $exhaustive_struct: ident,
644 $exhaustive_fn: ident,
645 $exhaustive_fn_from_single: ident,
646 $out_type: ty,
647 $([$i: tt, $out_x: ident]),*
648 ) => {
649 /// This documentation applies not only to `ExhaustivePairs1Input`, but also to
650 /// `ExhaustiveTriples1Input`, `ExhaustiveQuadruples1Input`, and so on. See
651 /// [`exhaustive_tuples_1_input`] for more information.
652 ///
653 /// Generates all $n$-tuples of a given length with elements from a single iterator.
654 #[derive(Clone, Debug)]
655 $($vis)* struct $exhaustive_struct<I: Iterator>
656 where
657 I::Item: Clone,
658 {
659 i: u64,
660 limit: Option<u64>,
661 distributor: BitDistributor,
662 xs: IteratorCache<I>,
663 xs_done: bool,
664 phantom: PhantomData<*const I::Item>,
665 }
666
667 impl<I: Iterator> Iterator for $exhaustive_struct<I>
668 where
669 I::Item: Clone,
670 {
671 type Item = $out_type;
672
673 fn next(&mut self) -> Option<Self::Item> {
674 if Some(self.i) == self.limit {
675 None
676 } else {
677 if self.i == u64::MAX {
678 panic!("Too many iterations");
679 }
680 loop {
681 let mut all_are_valid = true;
682 $(
683 if all_are_valid &&
684 self.xs.get(self.distributor.get_output($i)).is_none() {
685 all_are_valid = false;
686 }
687 )*
688 if all_are_valid {
689 break;
690 } else if !self.xs_done {
691 let xs_len = self.xs.known_len().unwrap();
692 $(
693 let _max_index = $i;
694 )*
695 let size = _max_index + 1;
696 self.limit = CheckedPow::checked_pow(
697 u64::exact_from(xs_len),
698 u64::exact_from(size)
699 );
700 if Some(self.i) == self.limit {
701 return None;
702 }
703 self.xs_done = true;
704 // xs_len > 0 at this point
705 self.distributor.set_max_bits(
706 &[0],
707 max(1, usize::wrapping_from((xs_len - 1).significant_bits())),
708 );
709 } else {
710 self.distributor.increment_counter();
711 }
712 }
713 let result = Some(
714 ($(self.xs.get(self.distributor.get_output($i)).unwrap().clone(),)*)
715 );
716 self.i += 1;
717 self.distributor.increment_counter();
718 result
719 }
720 }
721 }
722
723 /// This documentation applies not only to `exhaustive_pairs_1_input`, but also to
724 /// `exhaustive_triples_1_input`, `exhaustive_quadruples_1_input`, and so on. See
725 /// [`exhaustive_tuples_1_input`] for more information.
726 ///
727 /// Generates all length-$n$ tuples with elements from a single iterator.
728 ///
729 /// These functions differ from `exhaustive_[n-tuples]_from_single` in that different
730 /// [`BitDistributorOutputType`]s may be specified for each output element.
731 ///
732 /// The $i$th parameter `output_types_[x_i]` is a [`BitDistributorOutputType`] that
733 /// determines how quickly the $i$th output slot advances through the iterator; see the
734 /// [`BitDistributor`] documentation for a description of the different types.
735 ///
736 /// If `xs` is finite, the output length is $k^n$, where $k$ is `xs.count()` and $n$ is the
737 /// width of the tuples. If `xs` is infinite, the output is also infinite.
738 ///
739 /// If `xs` is empty, the output is also empty.
740 ///
741 /// # Examples
742 /// See [here](self#exhaustive_pairs_1_input).
743 #[allow(dead_code)]
744 $($vis)* fn $exhaustive_fn<I: Iterator>(
745 xs: I,
746 $($out_x: BitDistributorOutputType,)*
747 ) -> $exhaustive_struct<I>
748 where
749 I::Item: Clone,
750 {
751 $exhaustive_struct {
752 i: 0,
753 limit: None,
754 distributor: BitDistributor::new(&[$($out_x,)*]),
755 xs: IteratorCache::new(xs),
756 xs_done: false,
757 phantom: PhantomData,
758 }
759 }
760
761 /// This documentation applies not only to `exhaustive_pairs_from_single`, but also to
762 /// `exhaustive_triples_from_single`, `exhaustive_quadruples_from_single`, and so on. See
763 /// [`exhaustive_tuples_1_input`] for more information.
764 ///
765 /// Generates all $n$-tuples with elements from a single iterator.
766 ///
767 /// If `xs` is finite, the output length is $k^n$, where $k$ is `xs.count()` and $n$ is the
768 /// width of the tuples. If `xs` is infinite, the output is also infinite.
769 ///
770 /// If `xs` is empty, the output is also empty.
771 ///
772 /// # Examples
773 /// See [here](self#exhaustive_pairs_from_single).
774 #[allow(dead_code)]
775 #[inline]
776 $($vis)* fn $exhaustive_fn_from_single<I: Iterator>(xs: I) -> $exhaustive_struct<I>
777 where
778 I::Item: Clone,
779 {
780 $exhaustive_fn(xs, $(BitDistributorOutputType::normal(1 + $i * 0)),*)
781 }
782 }
783}
784exhaustive_tuples_1_input!(
785 (pub),
786 ExhaustivePairs1Input,
787 exhaustive_pairs_1_input,
788 exhaustive_pairs_from_single,
789 (I::Item, I::Item),
790 [0, output_type_x],
791 [1, output_type_y]
792);
793
794/// Defines exhaustive tuple generators.
795///
796/// Malachite provides [`exhaustive_pairs`] and [`exhaustive_pairs_custom_output`], but you can also
797/// define `exhaustive_triples`, `exhaustive_quadruples`, and so on, and
798/// `exhaustive_triples_custom_output`, `exhaustive_quadruples_custom_output`, and so on, in your
799/// program using the code below. The documentation for [`exhaustive_pairs`] and
800/// [`exhaustive_pairs_custom_output`] describes these other functions as well.
801///
802/// See usage examples [here](self#exhaustive_pairs) and
803/// [here](self#exhaustive_pairs_custom_output).
804///
805/// ```
806/// use malachite_base::exhaustive_tuples;
807/// use malachite_base::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
808/// use malachite_base::iterators::iterator_cache::IteratorCache;
809/// use malachite_base::num::conversion::traits::{ExactFrom, WrappingFrom};
810/// use malachite_base::num::logic::traits::SignificantBits;
811/// use std::cmp::max;
812///
813/// exhaustive_tuples!(
814/// (pub(crate)),
815/// ExhaustiveTriples,
816/// exhaustive_triples,
817/// exhaustive_triples_custom_output,
818/// [0, X, I, xs, xs_done, output_type_x],
819/// [1, Y, J, ys, ys_done, output_type_y],
820/// [2, Z, K, zs, zs_done, output_type_z]
821/// );
822/// exhaustive_tuples!(
823/// (pub(crate)),
824/// ExhaustiveQuadruples,
825/// exhaustive_quadruples,
826/// exhaustive_quadruples_custom_output,
827/// [0, X, I, xs, xs_done, output_type_x],
828/// [1, Y, J, ys, ys_done, output_type_y],
829/// [2, Z, K, zs, zs_done, output_type_z],
830/// [3, W, L, ws, ws_done, output_type_w]
831/// );
832/// exhaustive_tuples!(
833/// (pub(crate)),
834/// ExhaustiveQuintuples,
835/// exhaustive_quintuples,
836/// exhaustive_quintuples_custom_output,
837/// [0, X, I, xs, xs_done, output_type_x],
838/// [1, Y, J, ys, ys_done, output_type_y],
839/// [2, Z, K, zs, zs_done, output_type_z],
840/// [3, W, L, ws, ws_done, output_type_w],
841/// [4, V, M, vs, vs_done, output_type_v]
842/// );
843/// exhaustive_tuples!(
844/// (pub(crate)),
845/// ExhaustiveSextuples,
846/// exhaustive_sextuples,
847/// exhaustive_sextuples_custom_output,
848/// [0, X, I, xs, xs_done, output_type_x],
849/// [1, Y, J, ys, ys_done, output_type_y],
850/// [2, Z, K, zs, zs_done, output_type_z],
851/// [3, W, L, ws, ws_done, output_type_w],
852/// [4, V, M, vs, vs_done, output_type_v],
853/// [5, U, N, us, us_done, output_type_u]
854/// );
855/// exhaustive_tuples!(
856/// (pub(crate)),
857/// ExhaustiveSeptuples,
858/// exhaustive_septuples,
859/// exhaustive_septuples_custom_output,
860/// [0, X, I, xs, xs_done, output_type_x],
861/// [1, Y, J, ys, ys_done, output_type_y],
862/// [2, Z, K, zs, zs_done, output_type_z],
863/// [3, W, L, ws, ws_done, output_type_w],
864/// [4, V, M, vs, vs_done, output_type_v],
865/// [5, U, N, us, us_done, output_type_u],
866/// [6, T, O, ts, ts_done, output_type_t]
867/// );
868/// exhaustive_tuples!(
869/// (pub(crate)),
870/// ExhaustiveOctuples,
871/// exhaustive_octuples,
872/// exhaustive_octuples_custom_output,
873/// [0, X, I, xs, xs_done, output_type_x],
874/// [1, Y, J, ys, ys_done, output_type_y],
875/// [2, Z, K, zs, zs_done, output_type_z],
876/// [3, W, L, ws, ws_done, output_type_w],
877/// [4, V, M, vs, vs_done, output_type_v],
878/// [5, U, N, us, us_done, output_type_u],
879/// [6, T, O, ts, ts_done, output_type_t],
880/// [7, S, P, ss, ss_done, output_type_s]
881/// );
882/// ```
883#[macro_export]
884macro_rules! exhaustive_tuples {
885 (
886 ($($vis:tt)*),
887 $exhaustive_struct: ident,
888 $exhaustive_fn: ident,
889 $exhaustive_fn_custom_output: ident,
890 $([$i: tt, $t: ident, $it: ident, $xs: ident, $xs_done: ident, $out_x: ident]),*
891 ) => {
892 /// This documentation applies not only to `ExhaustivePairs`, but also to
893 /// `ExhaustiveTriples`, `ExhaustiveQuadruples`, and so on. See [`exhaustive_tuples`] for
894 /// more information.
895 ///
896 /// Generates all $n$-tuples with elements from $n$ iterators.
897 #[derive(Clone, Debug)]
898 $($vis)* struct $exhaustive_struct<$($t: Clone, $it: Iterator<Item = $t>,)*> {
899 i: u64,
900 limit: Option<u64>,
901 distributor: BitDistributor,
902 $(
903 $xs: IteratorCache<$it>,
904 $xs_done: bool,
905 )*
906 }
907
908 impl<$($t: Clone, $it: Iterator<Item = $t>,)*> $exhaustive_struct<$($t, $it,)*> {
909 fn try_getting_limit(&mut self) {
910 let mut all_limits_known = true;
911 $(
912 if let Some(xs_len) = self.$xs.known_len() {
913 if xs_len == 0 {
914 self.limit = Some(0);
915 return;
916 }
917 } else {
918 all_limits_known = false;
919 }
920 )*
921 if !all_limits_known {
922 return;
923 }
924 let mut product = 1u64;
925 $(
926 let xs_len = u64::exact_from(self.$xs.known_len().unwrap());
927 if let Some(new_product) = product.checked_mul(u64::exact_from(xs_len)) {
928 product = new_product;
929 } else {
930 return;
931 }
932 )*
933 self.limit = Some(product);
934 }
935 }
936
937 impl<$($t: Clone, $it: Iterator<Item = $t>,)*> Iterator for $exhaustive_struct<$($t, $it,)*>
938 {
939 type Item = ($($t,)*);
940
941 fn next(&mut self) -> Option<Self::Item> {
942 if Some(self.i) == self.limit {
943 None
944 } else {
945 if self.i == u64::MAX {
946 panic!("Too many iterations");
947 }
948 loop {
949 $(
950 if self.$xs.get(self.distributor.get_output($i)).is_none() {
951 if !self.$xs_done {
952 let xs_len = self.$xs.known_len().unwrap();
953 self.try_getting_limit();
954 if Some(self.i) == self.limit {
955 return None;
956 }
957 self.$xs_done = true;
958 self.distributor.set_max_bits(
959 &[$i],
960 max(
961 1,
962 usize::wrapping_from((xs_len - 1).significant_bits())
963 ),
964 );
965 } else {
966 self.distributor.increment_counter();
967 }
968 continue;
969 }
970 )*
971 break;
972 }
973 let result = Some(
974 ($(self.$xs.get(self.distributor.get_output($i)).unwrap().clone(),)*)
975 );
976 self.i += 1;
977 self.distributor.increment_counter();
978 result
979 }
980 }
981 }
982
983 /// This documentation applies not only to `exhaustive_pairs_custom_output`, but also to
984 /// `exhaustive_triples_custom_output`, `exhaustive_quadruples_custom_output`, and so on.
985 /// See [`exhaustive_tuples`] for more information.
986 ///
987 /// Generates all $n$-tuples with elements from $n$ iterators, possibly with different
988 /// output growth rates.
989 ///
990 /// The $i$th `output_type_[x_i]` parameter is a [`BitDistributorOutputType`] that
991 /// determines how quickly the $i$th output slot advances through its iterator; see the
992 /// [`BitDistributor`] documentation for a description of the different types.
993 ///
994 /// If all of `xs`, `ys`, `zs`, ... are finite, the output length is the product of their
995 /// lengths. If any of `xs`, `ys`, `zs`, ... are infinite, the output is also infinite.
996 ///
997 /// If any of `xs`, `ys`, `zs`, ... is empty, the output is also empty.
998 ///
999 /// # Examples
1000 /// See [here](self#exhaustive_pairs_custom_output).
1001 #[allow(dead_code)]
1002 $($vis)* fn $exhaustive_fn_custom_output<$($t: Clone, $it: Iterator<Item = $t>,)*>(
1003 $($xs: $it,)*
1004 $($out_x: BitDistributorOutputType,)*
1005 ) -> $exhaustive_struct<$($t, $it,)*> {
1006 $exhaustive_struct {
1007 i: 0,
1008 limit: None,
1009 distributor: BitDistributor::new(&[$($out_x,)*]),
1010 $(
1011 $xs: IteratorCache::new($xs),
1012 $xs_done: false,
1013 )*
1014 }
1015 }
1016
1017 /// This documentation applies not only to `exhaustive_pairs`, but also to
1018 /// `exhaustive_triples`, `exhaustive_quadruples`, and so on. See [`exhaustive_tuples`] for
1019 /// more information.
1020 ///
1021 /// Generates all $n$-tuples with elements from $n$ iterators.
1022 ///
1023 /// If all of `xs`, `ys`, `zs`, ... are finite, the output length is the product of their
1024 /// lengths. If any of `xs`, `ys`, `zs`, ... are infinite, the output is also infinite.
1025 ///
1026 /// If any of `xs`, `ys`, `zs`, ... is empty, the output is also empty.
1027 ///
1028 /// # Examples
1029 /// See [here](self#exhaustive_pairs).
1030 #[allow(dead_code)]
1031 #[inline]
1032 $($vis)* fn $exhaustive_fn<$($t: Clone, $it: Iterator<Item = $t>,)*>(
1033 $($xs: $it,)*
1034 ) -> $exhaustive_struct<$($t, $it,)*> {
1035 $exhaustive_fn_custom_output(
1036 $($xs,)*
1037 $(BitDistributorOutputType::normal(1 + 0 * $i),)*
1038 )
1039 }
1040 }
1041}
1042
1043exhaustive_tuples!(
1044 (pub),
1045 ExhaustivePairs,
1046 exhaustive_pairs,
1047 exhaustive_pairs_custom_output,
1048 [0, X, I, xs, xs_done, output_type_x],
1049 [1, Y, J, ys, ys_done, output_type_y]
1050);
1051
1052#[cfg(feature = "test_build")]
1053exhaustive_tuples!(
1054 (pub),
1055 ExhaustiveTriples,
1056 exhaustive_triples,
1057 exhaustive_triples_custom_output,
1058 [0, X, I, xs, xs_done, output_type_x],
1059 [1, Y, J, ys, ys_done, output_type_y],
1060 [2, Z, K, zs, zs_done, output_type_z]
1061);
1062
1063#[cfg(not(feature = "test_build"))]
1064exhaustive_tuples!(
1065 (pub(crate)),
1066 ExhaustiveTriples,
1067 exhaustive_triples,
1068 exhaustive_triples_custom_output,
1069 [0, X, I, xs, xs_done, output_type_x],
1070 [1, Y, J, ys, ys_done, output_type_y],
1071 [2, Z, K, zs, zs_done, output_type_z]
1072);
1073
1074#[cfg(feature = "test_build")]
1075exhaustive_tuples!(
1076 (pub),
1077 ExhaustiveQuadruples,
1078 exhaustive_quadruples,
1079 exhaustive_quadruples_custom_output,
1080 [0, X, I, xs, xs_done, output_type_x],
1081 [1, Y, J, ys, ys_done, output_type_y],
1082 [2, Z, K, zs, zs_done, output_type_z],
1083 [3, W, L, ws, ws_done, output_type_w]
1084);
1085
1086/// Defines custom exhaustive tuple generators.
1087///
1088/// You can define custom tuple generators like `exhaustive_triples_xyx` or
1089/// `exhaustive_triples_xyx_custom_output` in your program using the code below.
1090///
1091/// See usage examples [here](self#exhaustive_triples_xyx) and
1092/// [here](self#exhaustive_triples_xyx_custom_output).
1093///
1094/// ```
1095/// use malachite_base::custom_tuples;
1096/// use malachite_base::iterators::bit_distributor::{BitDistributor, BitDistributorOutputType};
1097/// use malachite_base::iterators::iterator_cache::IteratorCache;
1098/// use malachite_base::num::conversion::traits::{ExactFrom, WrappingFrom};
1099/// use malachite_base::num::logic::traits::SignificantBits;
1100/// use std::cmp::max;
1101///
1102/// #[allow(clippy::missing_const_for_fn)]
1103/// fn unwrap_triple<X, Y, Z>((a, b, c): (Option<X>, Option<Y>, Option<Z>)) -> (X, Y, Z) {
1104/// (a.unwrap(), b.unwrap(), c.unwrap())
1105/// }
1106///
1107/// #[allow(clippy::missing_const_for_fn)]
1108/// fn unwrap_quadruple<X, Y, Z, W>(
1109/// (a, b, c, d): (Option<X>, Option<Y>, Option<Z>, Option<W>),
1110/// ) -> (X, Y, Z, W) {
1111/// (a.unwrap(), b.unwrap(), c.unwrap(), d.unwrap())
1112/// }
1113///
1114/// #[allow(clippy::missing_const_for_fn)]
1115/// fn unwrap_quintuple<X, Y, Z, W, V>(
1116/// (a, b, c, d, e): (Option<X>, Option<Y>, Option<Z>, Option<W>, Option<V>),
1117/// ) -> (X, Y, Z, W, V) {
1118/// (a.unwrap(), b.unwrap(), c.unwrap(), d.unwrap(), e.unwrap())
1119/// }
1120///
1121/// custom_tuples!(
1122/// (pub),
1123/// ExhaustiveTriplesXXY,
1124/// (X, X, Y),
1125/// (None, None, None),
1126/// unwrap_triple,
1127/// exhaustive_triples_xxy,
1128/// exhaustive_triples_xxy_custom_output,
1129/// [X, I, xs, xs_done, [0, output_type_xs_0], [1, output_type_xs_1]],
1130/// [Y, J, ys, ys_done, [2, output_type_ys_2]]
1131/// );
1132/// custom_tuples!(
1133/// (pub),
1134/// ExhaustiveTriplesXYX,
1135/// (X, Y, X),
1136/// (None, None, None),
1137/// unwrap_triple,
1138/// exhaustive_triples_xyx,
1139/// exhaustive_triples_xyx_custom_output,
1140/// [X, I, xs, xs_done, [0, output_type_xs_0], [2, output_type_ys_1]],
1141/// [Y, J, ys, ys_done, [1, output_type_xs_2]]
1142/// );
1143/// custom_tuples!(
1144/// (pub),
1145/// ExhaustiveTriplesXYY,
1146/// (X, Y, Y),
1147/// (None, None, None),
1148/// unwrap_triple,
1149/// exhaustive_triples_xyy,
1150/// exhaustive_triples_xyy_custom_output,
1151/// [X, I, xs, xs_done, [0, output_type_xs_0]],
1152/// [Y, J, ys, ys_done, [1, output_type_ys_1], [2, output_type_ys_2]]
1153/// );
1154/// custom_tuples!(
1155/// (pub),
1156/// ExhaustiveQuadruplesXXXY,
1157/// (X, X, X, Y),
1158/// (None, None, None, None),
1159/// unwrap_quadruple,
1160/// exhaustive_quadruples_xxxy,
1161/// exhaustive_quadruples_xxxy_custom_output,
1162/// [X, I, xs, xs_done, [0, output_type_xs_0], [1, output_type_xs_1], [2, output_type_xs_2]],
1163/// [Y, J, ys, ys_done, [3, output_type_ys_3]]
1164/// );
1165/// custom_tuples!(
1166/// (pub),
1167/// ExhaustiveQuadruplesXXYX,
1168/// (X, X, Y, X),
1169/// (None, None, None, None),
1170/// unwrap_quadruple,
1171/// exhaustive_quadruples_xxyx,
1172/// exhaustive_quadruples_xxyx_custom_output,
1173/// [X, I, xs, xs_done, [0, output_type_xs_0], [1, output_type_xs_1], [3, output_type_xs_3]],
1174/// [Y, J, ys, ys_done, [2, output_type_ys_2]]
1175/// );
1176/// custom_tuples!(
1177/// (pub),
1178/// ExhaustiveQuadruplesXXYZ,
1179/// (X, X, Y, Z),
1180/// (None, None, None, None),
1181/// unwrap_quadruple,
1182/// exhaustive_quadruples_xxyz,
1183/// exhaustive_quadruples_xxyz_custom_output,
1184/// [X, I, xs, xs_done, [0, output_type_xs_0], [1, output_type_xs_1]],
1185/// [Y, J, ys, ys_done, [2, output_type_ys_2]],
1186/// [Z, K, zs, zs_done, [3, output_type_zs_3]]
1187/// );
1188/// custom_tuples!(
1189/// (pub),
1190/// ExhaustiveQuadruplesXYXZ,
1191/// (X, Y, X, Z),
1192/// (None, None, None, None),
1193/// unwrap_quadruple,
1194/// exhaustive_quadruples_xyxz,
1195/// exhaustive_quadruples_xyxz_custom_output,
1196/// [X, I, xs, xs_done, [0, output_type_xs_0], [2, output_type_xs_2]],
1197/// [Y, J, ys, ys_done, [1, output_type_ys_1]],
1198/// [Z, K, zs, zs_done, [3, output_type_zs_3]]
1199/// );
1200/// custom_tuples!(
1201/// (pub),
1202/// ExhaustiveQuadruplesXYYX,
1203/// (X, Y, Y, X),
1204/// (None, None, None, None),
1205/// unwrap_quadruple,
1206/// exhaustive_quadruples_xyyx,
1207/// exhaustive_quadruples_xyyx_custom_output,
1208/// [X, I, xs, xs_done, [0, output_type_xs_0], [3, output_type_xs_3]],
1209/// [Y, J, ys, ys_done, [1, output_type_ys_1], [2, output_type_ys_2]]
1210/// );
1211/// custom_tuples!(
1212/// (pub),
1213/// ExhaustiveQuadruplesXYYZ,
1214/// (X, Y, Y, Z),
1215/// (None, None, None, None),
1216/// unwrap_quadruple,
1217/// exhaustive_quadruples_xyyz,
1218/// exhaustive_quadruples_xyyz_custom_output,
1219/// [X, I, xs, xs_done, [0, output_type_xs_0]],
1220/// [Y, J, ys, ys_done, [1, output_type_ys_1], [2, output_type_ys_2]],
1221/// [Z, K, zs, zs_done, [3, output_type_zs_3]]
1222/// );
1223/// custom_tuples!(
1224/// (pub),
1225/// ExhaustiveQuadruplesXYZZ,
1226/// (X, Y, Z, Z),
1227/// (None, None, None, None),
1228/// unwrap_quadruple,
1229/// exhaustive_quadruples_xyzz,
1230/// exhaustive_quadruples_xyzz_custom_output,
1231/// [X, I, xs, xs_done, [0, output_type_xs_0]],
1232/// [Y, J, ys, ys_done, [1, output_type_ys_1]],
1233/// [Z, K, zs, zs_done, [2, output_type_zs_2], [3, output_type_zs_3]]
1234/// );
1235/// custom_tuples!(
1236/// (pub),
1237/// ExhaustiveQuintuplesXYYYZ,
1238/// (X, Y, Y, Y, Z),
1239/// (None, None, None, None, None),
1240/// unwrap_quintuple,
1241/// exhaustive_quintuples_xyyyz,
1242/// exhaustive_quintuples_xyyyz_custom_output,
1243/// [X, I, xs, xs_done, [0, output_type_xs_0]],
1244/// [Y, J, ys, ys_done, [1, output_type_ys_1], [2, output_type_ys_2], [3, output_type_ys_3]],
1245/// [Z, K, zs, zs_done, [4, output_type_zs_4]]
1246/// );
1247/// ```
1248#[macro_export]
1249macro_rules! custom_tuples {
1250 (
1251 ($($vis:tt)*),
1252 $exhaustive_struct: ident,
1253 $out_t: ty,
1254 $nones: expr,
1255 $unwrap_tuple: ident,
1256 $exhaustive_fn: ident,
1257 $exhaustive_custom_fn: ident,
1258 $([$t: ident, $it: ident, $xs: ident, $xs_done: ident, $([$i: tt, $out_x: ident]),*]),*
1259 ) => {
1260 // Generates all $n$-tuples with elements from $m$ iterators, where $m \leq n$.
1261 //
1262 // The mapping from iterators to tuple slots is indicated by the struct name; for example,
1263 // in `TriplesXYX` there are two iterators, `X`, and `Y`; `X` generates the elements in the
1264 // first and third slots of the output triples, and `Y` generates the elements in the second
1265 // slots.
1266 #[derive(Clone, Debug)]
1267 $($vis)* struct $exhaustive_struct<$($t: Clone, $it: Iterator<Item = $t>,)*> {
1268 i: u64,
1269 limit: Option<u64>,
1270 distributor: BitDistributor,
1271 $(
1272 $xs: IteratorCache<$it>,
1273 $xs_done: bool,
1274 )*
1275 }
1276
1277 impl<$($t: Clone, $it: Iterator<Item = $t>,)*> $exhaustive_struct<$($t, $it,)*> {
1278 fn try_getting_limit(&mut self) {
1279 let mut all_limits_known = true;
1280 $(
1281 if let Some(xs_len) = self.$xs.known_len() {
1282 if xs_len == 0 {
1283 self.limit = Some(0);
1284 return;
1285 }
1286 } else {
1287 all_limits_known = false;
1288 }
1289 )*
1290 if !all_limits_known {
1291 return;
1292 }
1293 let mut product = 1u64;
1294 $(
1295 let xs_len = u64::exact_from(self.$xs.known_len().unwrap());
1296 $(
1297 let _x = $i;
1298 if let Some(new_product) = product.checked_mul(xs_len) {
1299 product = new_product;
1300 } else {
1301 return;
1302 }
1303 )*
1304 )*
1305 self.limit = Some(product);
1306 }
1307 }
1308
1309 impl<$($t: Clone, $it: Iterator<Item = $t>,)*> Iterator
1310 for $exhaustive_struct<$($t, $it,)*>
1311 {
1312 type Item = $out_t;
1313
1314 fn next(&mut self) -> Option<Self::Item> {
1315 if Some(self.i) == self.limit {
1316 None
1317 } else {
1318 if self.i == u64::MAX {
1319 panic!("Too many iterations");
1320 }
1321 loop {
1322 $(
1323 $(
1324 if self.$xs.get(self.distributor.get_output($i)).is_none() {
1325 if !self.$xs_done {
1326 let xs_len = self.$xs.known_len().unwrap();
1327 self.try_getting_limit();
1328 if Some(self.i) == self.limit {
1329 return None;
1330 }
1331 self.$xs_done = true;
1332 self.distributor.set_max_bits(
1333 &[$i],
1334 max(
1335 1,
1336 usize::wrapping_from(
1337 (xs_len - 1).significant_bits()
1338 )
1339 ),
1340 );
1341 } else {
1342 self.distributor.increment_counter();
1343 }
1344 continue;
1345 }
1346 )*
1347 )*
1348 break;
1349 }
1350 let mut out = $nones;
1351 $(
1352 $(
1353 let x = self.$xs.get(self.distributor.get_output($i)).unwrap();
1354 out.$i = Some(x.clone());
1355 )*
1356 )*
1357 self.i += 1;
1358 self.distributor.increment_counter();
1359 Some($unwrap_tuple(out))
1360 }
1361 }
1362 }
1363
1364 // Generates all $n$-tuples with elements from $m$ iterators, where $m \leq n$, possibly
1365 // with different output growth rates.
1366 //
1367 // The mapping from iterators to tuple slots is indicated by the function name; for example,
1368 // `exhaustive_triples_xyx_custom_output` takes two iterators, `xs`, and `ys`; `xs`
1369 // generates the elements in the first and third slots of the output triples, and `ys`
1370 // generates the elements in the second slots.
1371 //
1372 // Let $i$ be the index of the input iterators and $j$ be the index of the output slots. So
1373 // for `exhaustive_triples_xyx_custom_output`, $i=0$ corresponds to $j=0$ and $j=2$, and
1374 // $i=1$ corresponds to $j=1$.
1375 //
1376 // The $j$th `output_type_[i_j]` parameter is a
1377 // [`BitDistributorOutputType`](crate::iterators::bit_distributor::BitDistributorOutputType)
1378 // that determines how quickly the $j$th output slot advances through its iterator; see the
1379 // [`BitDistributor`](crate::iterators::bit_distributor::BitDistributor) documentation for a
1380 // description of the different types.
1381 //
1382 // If all of `xs`, `ys`, `zs`, ... are finite, then the output length may be obtained by
1383 // raising the length of each input iterator to power of the number of outputs it maps to,
1384 // and taking the product of the resulting values.
1385 //
1386 // If any of `xs`, `ys`, `zs`, ... are infinite, the output is also infinite.
1387 //
1388 // If any of `xs`, `ys`, `zs`, ... is empty, the output is also empty.
1389 //
1390 // # Examples
1391 // See [here](self#exhaustive_triples_xyx_custom_output).
1392 #[allow(dead_code)]
1393 $($vis)* fn $exhaustive_custom_fn<$($t: Clone, $it: Iterator<Item = $t>,)*>(
1394 $($xs: $it,)*
1395 $($($out_x: BitDistributorOutputType,)*)*
1396 ) -> $exhaustive_struct<$($t, $it,)*> {
1397 $exhaustive_struct {
1398 i: 0,
1399 limit: None,
1400 distributor: BitDistributor::new(&[$($($out_x,)*)*]),
1401 $(
1402 $xs: IteratorCache::new($xs),
1403 $xs_done: false,
1404 )*
1405 }
1406 }
1407
1408 // Generates all $n$-tuples with elements from $m$ iterators, where $m \leq n$.
1409 //
1410 // The mapping from iterators to tuple slots is indicated by the function name; for example,
1411 // `exhaustive_triples_xyx` takes two iterators, `xs`, and `ys`; `xs` generates the elements
1412 // in the first and third slots of the output triples, and `ys` generates the elements in
1413 // the second slots.
1414 //
1415 // If all of `xs`, `ys`, `zs`, ... are finite, then the output length may be obtained by
1416 // raising the length of each input iterator to power of the number of outputs it maps to,
1417 // and taking the product of the resulting values.
1418 //
1419 // If any of `xs`, `ys`, `zs`, ... are infinite, the output is also infinite.
1420 //
1421 // If any of `xs`, `ys`, `zs`, ... is empty, the output is also empty.
1422 //
1423 // # Examples
1424 // See [here](self#exhaustive_triples_xyx).
1425 #[allow(dead_code)]
1426 #[inline]
1427 $($vis)* fn $exhaustive_fn<$($t: Clone, $it: Iterator<Item = $t>,)*>(
1428 $($xs: $it,)*
1429 ) -> $exhaustive_struct<$($t, $it,)*> {
1430 $exhaustive_custom_fn(
1431 $($xs,)*
1432 $($(BitDistributorOutputType::normal(1 + 0 * $i),)*)*
1433 )
1434 }
1435 }
1436}
1437
1438#[cfg(feature = "test_build")]
1439#[allow(clippy::missing_const_for_fn)]
1440fn unwrap_triple<X, Y, Z>((a, b, c): (Option<X>, Option<Y>, Option<Z>)) -> (X, Y, Z) {
1441 (a.unwrap(), b.unwrap(), c.unwrap())
1442}
1443
1444#[cfg(feature = "test_build")]
1445custom_tuples!(
1446 (pub),
1447 ExhaustiveTriplesXYY,
1448 (X, Y, Y),
1449 (None, None, None),
1450 unwrap_triple,
1451 exhaustive_triples_xyy,
1452 exhaustive_triples_xyy_custom_output,
1453 [X, I, xs, xs_done, [0, output_type_xs_0]],
1454 [Y, J, ys, ys_done, [1, output_type_ys_1], [2, output_type_ys_2]]
1455);
1456
1457/// A trait used by dependent-pairs structs.
1458///
1459/// Given a reference to an `x`, produces an iterator of `ys`.
1460///
1461/// See [`LexDependentPairs`] and [`ExhaustiveDependentPairs`].
1462pub trait ExhaustiveDependentPairsYsGenerator<X: Clone, Y, J: Iterator<Item = Y>> {
1463 fn get_ys(&self, x: &X) -> J;
1464}
1465
1466/// Generates pairs $(x, y)$, where the possible values of $y$ depend on the value of $x$. All $y$
1467/// values are output before proceeding to the next $x$.
1468///
1469/// This `struct` is created by; [`lex_dependent_pairs`]; see its documentation for more.
1470#[derive(Clone, Debug)]
1471pub struct LexDependentPairs<
1472 X: Clone,
1473 Y,
1474 S: ExhaustiveDependentPairsYsGenerator<X, Y, J>,
1475 I: Iterator<Item = X>,
1476 J: Iterator<Item = Y>,
1477> {
1478 done: bool,
1479 stop_after_empty_ys: bool,
1480 xs: I,
1481 ys: Option<J>,
1482 x: Option<X>,
1483 ys_generator: S,
1484}
1485
1486impl<
1487 X: Clone,
1488 Y,
1489 S: ExhaustiveDependentPairsYsGenerator<X, Y, J>,
1490 I: Iterator<Item = X>,
1491 J: Iterator<Item = Y>,
1492> LexDependentPairs<X, Y, S, I, J>
1493{
1494 fn advance_xs(&mut self) -> bool {
1495 if let Some(next_x) = self.xs.next() {
1496 self.x = Some(next_x);
1497 self.ys = Some(self.ys_generator.get_ys(self.x.as_ref().unwrap()));
1498 false
1499 } else {
1500 true
1501 }
1502 }
1503}
1504
1505impl<
1506 X: Clone,
1507 Y,
1508 S: ExhaustiveDependentPairsYsGenerator<X, Y, J>,
1509 I: Iterator<Item = X>,
1510 J: Iterator<Item = Y>,
1511> Iterator for LexDependentPairs<X, Y, S, I, J>
1512{
1513 type Item = (X, Y);
1514
1515 fn next(&mut self) -> Option<(X, Y)> {
1516 if self.done {
1517 None
1518 } else {
1519 let mut new_ys = false;
1520 if self.x.is_none() {
1521 if self.advance_xs() {
1522 self.done = true;
1523 return None;
1524 }
1525 new_ys = true;
1526 }
1527 loop {
1528 if let Some(y) = self.ys.as_mut().unwrap().next() {
1529 return Some((self.x.as_ref().unwrap().clone(), y));
1530 } else if self.stop_after_empty_ys && new_ys || self.advance_xs() {
1531 self.done = true;
1532 return None;
1533 }
1534 new_ys = true;
1535 }
1536 }
1537 }
1538}
1539
1540/// Generates pairs $(x, y)$, where the possible values of $y$ depend on the value of $x$. All $y$
1541/// values are output before proceeding to the next $x$.
1542///
1543/// This function takes an iterator `xs` that produces $x$ values, along with a `ys_generator` that
1544/// creates an iterator of $y$ values when given a reference to an $x$ value. The resulting iterator
1545/// first generates all pairs generated by the first $x$ value, then all pairs generated by the
1546/// second $x$ value, and so on.
1547///
1548/// It's called `lex_dependent_pairs` because if the `xs` iterator produces elements in some order,
1549/// and each `ys` iterator produces elements in some order (uniform across all `ys`), then the
1550/// resulting pairs are output in lexicographic order with respect to the $x$ and $y$ orders.
1551///
1552/// Each `ys` iterator produced by `ys_generator` must be finite; if some `ys` is infinite, then no
1553/// further `xs` value will be used. For a similar function that works with infinite `ys`, see
1554/// [`exhaustive_dependent_pairs`].
1555///
1556/// If, after a certain point, all the generated `ys` are empty, the output iterator will hang
1557/// trying to find another $(x, y)$ to output. To get around this, try
1558/// [`lex_dependent_pairs_stop_after_empty_ys`].
1559///
1560/// # Examples
1561/// ```
1562/// use itertools::Itertools;
1563/// use malachite_base::tuples::exhaustive::{
1564/// lex_dependent_pairs, ExhaustiveDependentPairsYsGenerator,
1565/// };
1566/// use maplit::hashmap;
1567/// use std::collections::HashMap;
1568/// use std::hash::Hash;
1569/// use std::iter::Cloned;
1570/// use std::slice::Iter;
1571///
1572/// #[derive(Clone, Debug)]
1573/// struct DPGeneratorFromMap<X: Clone + Eq + Hash, Y: 'static + Clone> {
1574/// map: HashMap<X, &'static [Y]>,
1575/// }
1576///
1577/// impl<X: Clone + Eq + Hash, Y: 'static + Clone>
1578/// ExhaustiveDependentPairsYsGenerator<X, Y, Cloned<Iter<'static, Y>>>
1579/// for DPGeneratorFromMap<X, Y>
1580/// {
1581/// #[inline]
1582/// fn get_ys(&self, x: &X) -> Cloned<Iter<'static, Y>> {
1583/// self.map[x].iter().cloned()
1584/// }
1585/// }
1586///
1587/// let xs = ["a", "b", "c", "b", "a"].iter().cloned();
1588/// let xss = lex_dependent_pairs(
1589/// xs,
1590/// DPGeneratorFromMap {
1591/// map: hashmap! {
1592/// "a" => &[2, 3, 4][..],
1593/// "b" => &[20][..],
1594/// "c" => &[30, 40][..]
1595/// },
1596/// },
1597/// )
1598/// .take(20)
1599/// .collect_vec();
1600/// assert_eq!(
1601/// xss.as_slice(),
1602/// &[
1603/// ("a", 2),
1604/// ("a", 3),
1605/// ("a", 4),
1606/// ("b", 20),
1607/// ("c", 30),
1608/// ("c", 40),
1609/// ("b", 20),
1610/// ("a", 2),
1611/// ("a", 3),
1612/// ("a", 4)
1613/// ]
1614/// );
1615///
1616/// let xs = [1, 2, 3, 2, 3, 2, 2].iter().cloned();
1617/// let xss = lex_dependent_pairs(
1618/// xs,
1619/// DPGeneratorFromMap {
1620/// map: hashmap! {
1621/// 1 => &[100, 101, 102][..],
1622/// 2 => &[][..],
1623/// 3 => &[300, 301, 302][..]
1624/// },
1625/// },
1626/// )
1627/// .take(20)
1628/// .collect_vec();
1629/// assert_eq!(
1630/// xss.as_slice(),
1631/// &[(1, 100), (1, 101), (1, 102), (3, 300), (3, 301), (3, 302), (3, 300), (3, 301), (3, 302),]
1632/// );
1633/// ```
1634#[inline]
1635pub const fn lex_dependent_pairs<
1636 X: Clone,
1637 Y,
1638 S: ExhaustiveDependentPairsYsGenerator<X, Y, J>,
1639 I: Iterator<Item = X>,
1640 J: Iterator<Item = Y>,
1641>(
1642 xs: I,
1643 ys_generator: S,
1644) -> LexDependentPairs<X, Y, S, I, J> {
1645 LexDependentPairs {
1646 done: false,
1647 stop_after_empty_ys: false,
1648 xs,
1649 ys: None,
1650 x: None,
1651 ys_generator,
1652 }
1653}
1654
1655/// Generates pairs $(x, y)$, where the possible values of $y$ depend on the value of $x$. $x$
1656/// values with no corresponding $y$ values are treated specially.
1657///
1658/// See [`lex_dependent_pairs`] for context.
1659///
1660/// If the output iterator encounters an $x$ value whose corresponding `ys` iterator is empty, the
1661/// output iterator stops iterating altogether. This prevents the iterator from getting stuck if all
1662/// `ys` iterators after a certain point are empty.
1663///
1664/// # Examples
1665/// ```
1666/// use itertools::Itertools;
1667/// use malachite_base::tuples::exhaustive::{
1668/// lex_dependent_pairs_stop_after_empty_ys, ExhaustiveDependentPairsYsGenerator,
1669/// };
1670/// use maplit::hashmap;
1671/// use std::collections::HashMap;
1672/// use std::hash::Hash;
1673/// use std::iter::Cloned;
1674/// use std::slice::Iter;
1675///
1676/// #[derive(Clone, Debug)]
1677/// struct DPGeneratorFromMap<X: Clone + Eq + Hash, Y: 'static + Clone> {
1678/// map: HashMap<X, &'static [Y]>,
1679/// }
1680///
1681/// impl<X: Clone + Eq + Hash, Y: 'static + Clone>
1682/// ExhaustiveDependentPairsYsGenerator<X, Y, Cloned<Iter<'static, Y>>>
1683/// for DPGeneratorFromMap<X, Y>
1684/// {
1685/// #[inline]
1686/// fn get_ys(&self, x: &X) -> Cloned<Iter<'static, Y>> {
1687/// self.map[x].iter().cloned()
1688/// }
1689/// }
1690///
1691/// let xs = [1, 2, 3, 2, 3, 2, 2].iter().cloned();
1692/// let xss = lex_dependent_pairs_stop_after_empty_ys(
1693/// xs,
1694/// DPGeneratorFromMap {
1695/// map: hashmap! {
1696/// 1 => &[100, 101, 102][..],
1697/// 2 => &[][..],
1698/// 3 => &[300, 301, 302][..]
1699/// },
1700/// },
1701/// )
1702/// .take(20)
1703/// .collect_vec();
1704/// // Stops after seeing 2, which maps to an empty iterator
1705/// assert_eq!(xss.as_slice(), &[(1, 100), (1, 101), (1, 102)]);
1706/// ```
1707#[inline]
1708pub const fn lex_dependent_pairs_stop_after_empty_ys<
1709 X: Clone,
1710 Y,
1711 S: ExhaustiveDependentPairsYsGenerator<X, Y, J>,
1712 I: Iterator<Item = X>,
1713 J: Iterator<Item = Y>,
1714>(
1715 xs: I,
1716 ys_generator: S,
1717) -> LexDependentPairs<X, Y, S, I, J> {
1718 LexDependentPairs {
1719 done: false,
1720 stop_after_empty_ys: true,
1721 xs,
1722 ys: None,
1723 x: None,
1724 ys_generator,
1725 }
1726}
1727
1728/// Generates pairs $(x, y)$, where the possible values of $y$ depend on the value of $x$.
1729///
1730/// This `struct` is created by [`exhaustive_dependent_pairs`]; see its documentation for more.
1731#[derive(Clone, Debug)]
1732pub struct ExhaustiveDependentPairs<
1733 X: Clone,
1734 Y,
1735 G: Iterator<Item = usize>,
1736 S: ExhaustiveDependentPairsYsGenerator<X, Y, J>,
1737 I: Iterator<Item = X>,
1738 J: Iterator<Item = Y>,
1739> {
1740 done: bool,
1741 xs_done: bool,
1742 stop_after_empty_ys: bool,
1743 index_generator: G,
1744 xs: I,
1745 xs_yss: Vec<(X, J, bool)>,
1746 ys_generator: S,
1747}
1748
1749impl<
1750 X: Clone,
1751 Y,
1752 G: Iterator<Item = usize>,
1753 S: ExhaustiveDependentPairsYsGenerator<X, Y, J>,
1754 I: Iterator<Item = X>,
1755 J: Iterator<Item = Y>,
1756> Iterator for ExhaustiveDependentPairs<X, Y, G, S, I, J>
1757{
1758 type Item = (X, Y);
1759
1760 fn next(&mut self) -> Option<(X, Y)> {
1761 if self.done {
1762 None
1763 } else {
1764 let original_i = self.index_generator.next().unwrap();
1765 loop {
1766 let mut i = original_i;
1767 let mut xs_yss_len = self.xs_yss.len();
1768 if self.xs_done {
1769 i %= xs_yss_len;
1770 } else if i >= xs_yss_len {
1771 for x in (&mut self.xs).take(i - xs_yss_len + 1) {
1772 let ys = self.ys_generator.get_ys(&x);
1773 self.xs_yss.push((x, ys, true));
1774 }
1775 xs_yss_len = self.xs_yss.len();
1776 if xs_yss_len == 0 {
1777 self.done = true;
1778 return None;
1779 } else if i >= xs_yss_len {
1780 self.xs_done = true;
1781 i %= xs_yss_len;
1782 }
1783 }
1784 let t = &mut self.xs_yss[i];
1785 if let Some(y) = t.1.next() {
1786 // t has been used
1787 t.2 = false;
1788 return Some((t.0.clone(), y));
1789 } else if self.stop_after_empty_ys && t.2 {
1790 self.done = true;
1791 return None;
1792 }
1793 self.xs_yss.remove(i);
1794 if self.xs_done && self.xs_yss.is_empty() {
1795 self.done = true;
1796 return None;
1797 }
1798 }
1799 }
1800 }
1801}
1802
1803/// Generates pairs $(x, y)$, where the possible values of $y$ depend on the value of $x$.
1804///
1805/// This function takes an iterator `xs` that produces $x$ values, along with a `ys_generator` that
1806/// creates an iterator of $y$ values when given a reference to an $x$ value. The resulting iterator
1807/// does not use all of an $x$'s $y$s immediately. Instead, it uses an `index_generator` (an
1808/// iterator of `usize`s) to determine which $x$ value's iterator should be advanced. This
1809/// arrangement allows for an $x$ to map to infinitely many `ys`.
1810///
1811/// `index_generator` must generate every natural number infinitely many times. Good generators can
1812/// be created using [`ruler_sequence`](crate::num::iterators::ruler_sequence) or
1813/// [`bit_distributor_sequence`](crate::num::iterators::bit_distributor_sequence). The slower the
1814/// sequence's growth rate, the more this iterator will prefer to use initial $x$ values before
1815/// exploring later ones.
1816///
1817/// If you want all of an $x$ value's $y$s to be used before moving on to the next $x$, use
1818/// [`lex_dependent_pairs`] instead.
1819///
1820/// If, after a certain point, all the generated `ys` are empty, the output iterator will hang
1821/// trying to find another $(x, y)$ to output. To get around this, try
1822/// [`exhaustive_dependent_pairs_stop_after_empty_ys`].
1823///
1824/// # Examples
1825/// ```
1826/// use itertools::Itertools;
1827/// use malachite_base::num::exhaustive::exhaustive_positive_primitive_ints;
1828/// use malachite_base::num::iterators::ruler_sequence;
1829/// use malachite_base::tuples::exhaustive::{
1830/// exhaustive_dependent_pairs, ExhaustiveDependentPairsYsGenerator,
1831/// };
1832/// use maplit::hashmap;
1833/// use std::collections::HashMap;
1834/// use std::hash::Hash;
1835/// use std::iter::Cloned;
1836/// use std::slice::Iter;
1837///
1838/// #[derive(Clone, Debug)]
1839/// pub struct MultiplesGeneratorHelper {
1840/// u: u64,
1841/// step: u64,
1842/// }
1843///
1844/// impl Iterator for MultiplesGeneratorHelper {
1845/// type Item = u64;
1846///
1847/// fn next(&mut self) -> Option<u64> {
1848/// let next = self.u;
1849/// self.u += self.step;
1850/// Some(next)
1851/// }
1852/// }
1853///
1854/// #[derive(Clone, Debug)]
1855/// struct MultiplesGenerator {}
1856///
1857/// impl ExhaustiveDependentPairsYsGenerator<u64, u64, MultiplesGeneratorHelper>
1858/// for MultiplesGenerator
1859/// {
1860/// #[inline]
1861/// fn get_ys(&self, x: &u64) -> MultiplesGeneratorHelper {
1862/// MultiplesGeneratorHelper { u: *x, step: *x }
1863/// }
1864/// }
1865///
1866/// #[derive(Clone, Debug)]
1867/// struct DPGeneratorFromMap<X: Clone + Eq + Hash, Y: 'static + Clone> {
1868/// map: HashMap<X, &'static [Y]>,
1869/// }
1870///
1871/// impl<X: Clone + Eq + Hash, Y: 'static + Clone>
1872/// ExhaustiveDependentPairsYsGenerator<X, Y, Cloned<Iter<'static, Y>>>
1873/// for DPGeneratorFromMap<X, Y>
1874/// {
1875/// #[inline]
1876/// fn get_ys(&self, x: &X) -> Cloned<Iter<'static, Y>> {
1877/// self.map[x].iter().cloned()
1878/// }
1879/// }
1880///
1881/// // All (x, y) where x is a positive natural and y is a positive multiple of x. It would be
1882/// // easier to do
1883/// //
1884/// // exhaustive_pairs_from_single(exhaustive_positive_primitive_ints::<u64>())
1885/// // .map(|(x, y)| (x, x * y))
1886/// //
1887/// // in this case.
1888/// let xs = exhaustive_positive_primitive_ints::<u64>();
1889/// let xss = exhaustive_dependent_pairs(ruler_sequence(), xs.clone(), MultiplesGenerator {})
1890/// .take(50)
1891/// .collect_vec();
1892/// assert_eq!(
1893/// xss.as_slice(),
1894/// &[
1895/// (1, 1),
1896/// (2, 2),
1897/// (1, 2),
1898/// (3, 3),
1899/// (1, 3),
1900/// (2, 4),
1901/// (1, 4),
1902/// (4, 4),
1903/// (1, 5),
1904/// (2, 6),
1905/// (1, 6),
1906/// (3, 6),
1907/// (1, 7),
1908/// (2, 8),
1909/// (1, 8),
1910/// (5, 5),
1911/// (1, 9),
1912/// (2, 10),
1913/// (1, 10),
1914/// (3, 9),
1915/// (1, 11),
1916/// (2, 12),
1917/// (1, 12),
1918/// (4, 8),
1919/// (1, 13),
1920/// (2, 14),
1921/// (1, 14),
1922/// (3, 12),
1923/// (1, 15),
1924/// (2, 16),
1925/// (1, 16),
1926/// (6, 6),
1927/// (1, 17),
1928/// (2, 18),
1929/// (1, 18),
1930/// (3, 15),
1931/// (1, 19),
1932/// (2, 20),
1933/// (1, 20),
1934/// (4, 12),
1935/// (1, 21),
1936/// (2, 22),
1937/// (1, 22),
1938/// (3, 18),
1939/// (1, 23),
1940/// (2, 24),
1941/// (1, 24),
1942/// (5, 10),
1943/// (1, 25),
1944/// (2, 26)
1945/// ]
1946/// );
1947///
1948/// let xs = [1, 2, 3, 2, 3, 2, 2].iter().cloned();
1949/// let xss = exhaustive_dependent_pairs(
1950/// ruler_sequence(),
1951/// xs,
1952/// DPGeneratorFromMap {
1953/// map: hashmap! { 1 => &[100, 101, 102][..], 2 => &[][..], 3 => &[300, 301, 302][..] },
1954/// },
1955/// )
1956/// .take(20)
1957/// .collect_vec();
1958/// assert_eq!(
1959/// xss.as_slice(),
1960/// &[(1, 100), (3, 300), (1, 101), (3, 300), (1, 102), (3, 301), (3, 302), (3, 301), (3, 302)]
1961/// );
1962/// ```
1963#[inline]
1964pub const fn exhaustive_dependent_pairs<
1965 X: Clone,
1966 Y,
1967 G: Iterator<Item = usize>,
1968 S: ExhaustiveDependentPairsYsGenerator<X, Y, J>,
1969 I: Iterator<Item = X>,
1970 J: Iterator<Item = Y>,
1971>(
1972 index_generator: G,
1973 xs: I,
1974 ys_generator: S,
1975) -> ExhaustiveDependentPairs<X, Y, G, S, I, J> {
1976 ExhaustiveDependentPairs {
1977 done: false,
1978 xs_done: false,
1979 stop_after_empty_ys: false,
1980 index_generator,
1981 xs,
1982 xs_yss: Vec::new(),
1983 ys_generator,
1984 }
1985}
1986
1987/// Generates pairs $(x, y)$, where the possible values of $y$ depend on the value of $x$. $x$
1988/// values with no corresponding $y$ values are treated specially.
1989///
1990/// See [`exhaustive_dependent_pairs`] for context.
1991///
1992/// If the output iterator encounters an $x$ value whose corresponding `ys` iterator is empty, the
1993/// output iterator stops iterating altogether. This prevents the iterator from getting stuck if all
1994/// `ys` iterators after a certain point are empty.
1995///
1996/// # Examples
1997/// ```
1998/// use itertools::Itertools;
1999/// use malachite_base::num::iterators::ruler_sequence;
2000/// use malachite_base::tuples::exhaustive::{
2001/// exhaustive_dependent_pairs_stop_after_empty_ys, ExhaustiveDependentPairsYsGenerator,
2002/// };
2003/// use maplit::hashmap;
2004/// use std::collections::HashMap;
2005/// use std::hash::Hash;
2006/// use std::iter::Cloned;
2007/// use std::slice::Iter;
2008///
2009/// #[derive(Clone, Debug)]
2010/// pub struct MultiplesGeneratorHelper {
2011/// u: u64,
2012/// step: u64,
2013/// }
2014///
2015/// impl Iterator for MultiplesGeneratorHelper {
2016/// type Item = u64;
2017///
2018/// fn next(&mut self) -> Option<u64> {
2019/// let next = self.u;
2020/// self.u += self.step;
2021/// Some(next)
2022/// }
2023/// }
2024///
2025/// #[derive(Clone, Debug)]
2026/// struct DPGeneratorFromMap<X: Clone + Eq + Hash, Y: 'static + Clone> {
2027/// map: HashMap<X, &'static [Y]>,
2028/// }
2029///
2030/// impl<X: Clone + Eq + Hash, Y: 'static + Clone>
2031/// ExhaustiveDependentPairsYsGenerator<X, Y, Cloned<Iter<'static, Y>>>
2032/// for DPGeneratorFromMap<X, Y>
2033/// {
2034/// #[inline]
2035/// fn get_ys(&self, x: &X) -> Cloned<Iter<'static, Y>> {
2036/// self.map[x].iter().cloned()
2037/// }
2038/// }
2039///
2040/// let xs = [1, 2, 3, 2, 3, 2, 2].iter().cloned();
2041/// let xss = exhaustive_dependent_pairs_stop_after_empty_ys(
2042/// ruler_sequence(),
2043/// xs,
2044/// DPGeneratorFromMap {
2045/// map: hashmap! {
2046/// 1 => &[100, 101, 102][..],
2047/// 2 => &[][..],
2048/// 3 => &[300, 301, 302][..]
2049/// },
2050/// },
2051/// )
2052/// .take(20)
2053/// .collect_vec();
2054/// assert_eq!(xss.as_slice(), &[(1, 100)]);
2055/// ```
2056#[inline]
2057pub const fn exhaustive_dependent_pairs_stop_after_empty_ys<
2058 X: Clone,
2059 Y,
2060 G: Iterator<Item = usize>,
2061 S: ExhaustiveDependentPairsYsGenerator<X, Y, J>,
2062 I: Iterator<Item = X>,
2063 J: Iterator<Item = Y>,
2064>(
2065 index_generator: G,
2066 xs: I,
2067 ys_generator: S,
2068) -> ExhaustiveDependentPairs<X, Y, G, S, I, J> {
2069 ExhaustiveDependentPairs {
2070 done: false,
2071 xs_done: false,
2072 stop_after_empty_ys: true,
2073 index_generator,
2074 xs,
2075 xs_yss: Vec::new(),
2076 ys_generator,
2077 }
2078}
2079
2080/// Defines lexicographic ordered unique tuple generators.
2081///
2082/// Malachite provides [`lex_ordered_unique_pairs`], but you can also define
2083/// `lex_ordered_unique_triples`, `lex_ordered_unique_quadruples`, and so on, in your program using
2084/// the code below. The documentation for [`lex_ordered_unique_pairs`] describes these other
2085/// functions as well.
2086///
2087/// See usage examples [here](self#lex_ordered_unique_quadruples).
2088///
2089/// ```
2090/// use malachite_base::iterators::iterator_cache::IteratorCache;
2091/// use malachite_base::lex_ordered_unique_tuples;
2092/// use malachite_base::vecs::exhaustive::fixed_length_ordered_unique_indices_helper;
2093/// use std::marker::PhantomData;
2094///
2095/// lex_ordered_unique_tuples!(
2096/// (pub(crate)),
2097/// LexOrderedUniqueTriples,
2098/// 3,
2099/// (I::Item, I::Item, I::Item),
2100/// lex_ordered_unique_triples,
2101/// [0, 1, 2]
2102/// );
2103/// lex_ordered_unique_tuples!(
2104/// (pub(crate)),
2105/// LexOrderedUniqueQuadruples,
2106/// 4,
2107/// (I::Item, I::Item, I::Item, I::Item),
2108/// lex_ordered_unique_quadruples,
2109/// [0, 1, 2, 3]
2110/// );
2111/// lex_ordered_unique_tuples!(
2112/// (pub(crate)),
2113/// LexOrderedUniqueQuintuples,
2114/// 5,
2115/// (I::Item, I::Item, I::Item, I::Item, I::Item),
2116/// lex_ordered_unique_quintuples,
2117/// [0, 1, 2, 3, 4]
2118/// );
2119/// lex_ordered_unique_tuples!(
2120/// (pub(crate)),
2121/// LexOrderedUniqueSextuples,
2122/// 6,
2123/// (I::Item, I::Item, I::Item, I::Item, I::Item, I::Item),
2124/// lex_ordered_unique_sextuples,
2125/// [0, 1, 2, 3, 4, 5]
2126/// );
2127/// lex_ordered_unique_tuples!(
2128/// (pub(crate)),
2129/// LexOrderedUniqueSeptuples,
2130/// 7,
2131/// (
2132/// I::Item,
2133/// I::Item,
2134/// I::Item,
2135/// I::Item,
2136/// I::Item,
2137/// I::Item,
2138/// I::Item
2139/// ),
2140/// lex_ordered_unique_septuples,
2141/// [0, 1, 2, 3, 4, 5, 6]
2142/// );
2143/// lex_ordered_unique_tuples!(
2144/// (pub(crate)),
2145/// LexOrderedUniqueOctuples,
2146/// 8,
2147/// (
2148/// I::Item,
2149/// I::Item,
2150/// I::Item,
2151/// I::Item,
2152/// I::Item,
2153/// I::Item,
2154/// I::Item,
2155/// I::Item
2156/// ),
2157/// lex_ordered_unique_octuples,
2158/// [0, 1, 2, 3, 4, 5, 6, 7]
2159/// );
2160/// ```
2161#[macro_export]
2162macro_rules! lex_ordered_unique_tuples {
2163 (
2164 ($($vis:tt)*),
2165 $struct: ident,
2166 $k: expr,
2167 $out_t: ty,
2168 $fn: ident,
2169 [$($i: expr),*]
2170 ) => {
2171 /// This documentation applies not only to `LexOrderedUniquePairs`, but also to
2172 /// `LexOrderedUniqueTriples`, `LexOrderedUniqueQuadruples`, and so on. See
2173 /// [`lex_ordered_unique_tuples`] for more information.
2174 ///
2175 /// Generates all $k$-tuples of elements from an iterator, where the tuples have no
2176 /// repetitions and are ordered the same way as in the iterator.
2177 ///
2178 /// The tuples are generated in lexicographic order with respect to the order of the element
2179 /// iterator.
2180 #[derive(Clone, Debug)]
2181 $($vis)* struct $struct<I: Iterator> where I::Item: Clone {
2182 first: bool,
2183 done: bool,
2184 xs: IteratorCache<I>,
2185 indices: [usize; $k],
2186 phantom: PhantomData<*const I::Item>,
2187 }
2188
2189 impl<I: Iterator> Iterator for $struct<I> where I::Item: Clone {
2190 type Item = $out_t;
2191
2192 fn next(&mut self) -> Option<Self::Item> {
2193 if self.done {
2194 return None;
2195 }
2196 if self.first {
2197 self.first = false;
2198 self.xs.get($k);
2199 if let Some(n) = self.xs.known_len() {
2200 if n < $k {
2201 self.done = true;
2202 return None;
2203 }
2204 }
2205 } else {
2206 if let Some(n) = self.xs.known_len() {
2207 if fixed_length_ordered_unique_indices_helper(n, $k, &mut self.indices) {
2208 self.done = true;
2209 return None;
2210 }
2211 } else {
2212 *self.indices.last_mut().unwrap() += 1;
2213 }
2214 }
2215 if let Some(&last_index) = self.indices.last() {
2216 // Give known len a chance to be set
2217 self.xs.get(last_index + 1);
2218 }
2219 Some(($(self.xs.assert_get(self.indices[$i]).clone(),)*))
2220 }
2221 }
2222
2223 /// This documentation applies not only to `lex_ordered_unique_pairs`, but also to
2224 /// `lex_ordered_unique_triples`, `lex_ordered_unique_quadruples`, and so on. See
2225 /// [`lex_ordered_unique_tuples`] for more information.
2226 ///
2227 /// Generates $k$-tuples of elements from a single iterator, such that each tuple has no
2228 /// repeated elements, and the elements in each [`Vec`] are ordered the same way as they are
2229 /// in the source iterator.
2230 ///
2231 /// The source iterator should not repeat any elements, but this is not enforced.
2232 ///
2233 /// The order is lexicographic with respect to the order of the element iterator.
2234 ///
2235 /// If the input iterator is infinite, the output length is also infinite.
2236 ///
2237 /// If the input iterator length is $n$, the output length is $\binom{n}{k}$.
2238 ///
2239 /// If `xs` is empty, the output is also empty.
2240 ///
2241 /// # Examples
2242 /// See [here](self#lex_ordered_unique_quadruples).
2243 $($vis)* const fn $fn<I: Iterator>(xs: I) -> $struct<I> where I::Item: Clone {
2244 $struct {
2245 first: true,
2246 done: false,
2247 xs: IteratorCache::new(xs),
2248 indices: [$($i),*],
2249 phantom: PhantomData,
2250 }
2251 }
2252 }
2253}
2254
2255lex_ordered_unique_tuples!(
2256 (pub),
2257 LexOrderedUniquePairs,
2258 2,
2259 (I::Item, I::Item),
2260 lex_ordered_unique_pairs,
2261 [0, 1]
2262);
2263
2264/// Defines exhaustive ordered unique tuple generators.
2265///
2266/// Malachite provides [`exhaustive_ordered_unique_pairs`], but you can also define
2267/// `exhaustive_ordered_unique_triples`, `exhaustive_ordered_unique_quadruples`, and so on, in your
2268/// program using the code below. The documentation for [`exhaustive_ordered_unique_pairs`]
2269/// describes these other functions as well.
2270///
2271/// See usage examples [here](self#exhaustive_ordered_unique_quadruples).
2272///
2273/// ```
2274/// use malachite_base::exhaustive_ordered_unique_tuples;
2275/// use malachite_base::iterators::iterator_cache::IteratorCache;
2276/// use malachite_base::vecs::exhaustive::next_bit_pattern;
2277///
2278/// exhaustive_ordered_unique_tuples!(
2279/// (pub(crate)),
2280/// ExhaustiveOrderedUniqueTriples,
2281/// 3,
2282/// (I::Item, I::Item, I::Item),
2283/// exhaustive_ordered_unique_triples,
2284/// [0, 1, 2]
2285/// );
2286/// exhaustive_ordered_unique_tuples!(
2287/// (pub(crate)),
2288/// ExhaustiveOrderedUniqueQuadruples,
2289/// 4,
2290/// (I::Item, I::Item, I::Item, I::Item),
2291/// exhaustive_ordered_unique_quadruples,
2292/// [0, 1, 2, 3]
2293/// );
2294/// exhaustive_ordered_unique_tuples!(
2295/// (pub(crate)),
2296/// ExhaustiveOrderedUniqueQuintuples,
2297/// 5,
2298/// (I::Item, I::Item, I::Item, I::Item, I::Item),
2299/// exhaustive_ordered_unique_quintuples,
2300/// [0, 1, 2, 3, 4]
2301/// );
2302/// exhaustive_ordered_unique_tuples!(
2303/// (pub(crate)),
2304/// ExhaustiveOrderedUniqueSextuples,
2305/// 6,
2306/// (I::Item, I::Item, I::Item, I::Item, I::Item, I::Item),
2307/// exhaustive_ordered_unique_sextuples,
2308/// [0, 1, 2, 3, 4, 5]
2309/// );
2310/// exhaustive_ordered_unique_tuples!(
2311/// (pub(crate)),
2312/// ExhaustiveOrderedUniqueSeptuples,
2313/// 7,
2314/// (
2315/// I::Item,
2316/// I::Item,
2317/// I::Item,
2318/// I::Item,
2319/// I::Item,
2320/// I::Item,
2321/// I::Item
2322/// ),
2323/// exhaustive_ordered_unique_septuples,
2324/// [0, 1, 2, 3, 4, 5, 6]
2325/// );
2326/// exhaustive_ordered_unique_tuples!(
2327/// (pub(crate)),
2328/// ExhaustiveOrderedUniqueOctuples,
2329/// 8,
2330/// (
2331/// I::Item,
2332/// I::Item,
2333/// I::Item,
2334/// I::Item,
2335/// I::Item,
2336/// I::Item,
2337/// I::Item,
2338/// I::Item
2339/// ),
2340/// exhaustive_ordered_unique_octuples,
2341/// [0, 1, 2, 3, 4, 5, 6, 7]
2342/// );
2343/// ```
2344#[macro_export]
2345macro_rules! exhaustive_ordered_unique_tuples {
2346 (
2347 ($($vis:tt)*),
2348 $struct: ident,
2349 $k: expr,
2350 $out_t: ty,
2351 $fn: ident,
2352 [$($i: expr),*]
2353 ) => {
2354 /// This documentation applies not only to `ExhaustiveOrderedUniquePairs`, but also to
2355 /// `ExhaustiveOrderedUniqueTriples`, `ExhaustiveOrderedUniqueQuadruples`, and so on. See
2356 /// [`exhaustive_ordered_unique_tuples`] for more information.
2357 ///
2358 /// Generates all $k$-tuples of elements from an iterator, where the tuples have no
2359 /// repetitions and are ordered the same way as in the iterator.
2360 #[derive(Clone)]
2361 pub struct $struct<I: Iterator>
2362 where
2363 I::Item: Clone,
2364 {
2365 done: bool,
2366 first: bool,
2367 xs: IteratorCache<I>,
2368 pattern: Vec<bool>,
2369 }
2370
2371 impl<I: Iterator> Iterator for $struct<I>
2372 where
2373 I::Item: Clone,
2374 {
2375 type Item = $out_t;
2376
2377 fn next(&mut self) -> Option<Self::Item> {
2378 if self.done {
2379 return None;
2380 } else if self.first {
2381 self.first = false;
2382 } else {
2383 let mut c = $k;
2384 next_bit_pattern(&mut self.pattern, &mut c, $k, $k);
2385 }
2386 if !self.pattern.is_empty() && self.xs.get(self.pattern.len() - 1).is_none() {
2387 self.done = true;
2388 return None;
2389 }
2390 let mut results = self.pattern.iter().enumerate().filter_map(|(i, &b)| {
2391 if b {
2392 Some(self.xs.assert_get(i).clone())
2393 } else {
2394 None
2395 }
2396 });
2397 Some(($(((results.next().unwrap(), $i).0)),*))
2398 }
2399 }
2400
2401 /// This documentation applies not only to `exhaustive_ordered_unique_pairs`, but also to
2402 /// `exhaustive_ordered_unique_triples`, `exhaustive_ordered_unique_quadruples`, and so on.
2403 /// See [`exhaustive_ordered_unique_tuples`] for more information.
2404 ///
2405 /// Generates $k$-tuples of elements from a single iterator, such that each tuple has no
2406 /// repeated elements, and the elements in each [`Vec`] are ordered the same way as they are
2407 /// in the source iterator.
2408 ///
2409 /// The source iterator should not repeat any elements, but this is not enforced.
2410 ///
2411 /// If the input iterator is infinite, the output length is also infinite.
2412 ///
2413 /// If the input iterator length is $n$, the output length is $\binom{n}{k}$.
2414 ///
2415 /// If `xs` is empty, the output is also empty.
2416 ///
2417 /// # Examples
2418 /// See [here](self#exhaustive_ordered_unique_quadruples).
2419 pub fn $fn<I: Iterator>(xs: I) -> $struct<I>
2420 where
2421 I::Item: Clone,
2422 {
2423 $struct {
2424 done: false,
2425 first: true,
2426 xs: IteratorCache::new(xs),
2427 pattern: vec![true; $k],
2428 }
2429 }
2430 }
2431}
2432exhaustive_ordered_unique_tuples!(
2433 (pub),
2434 ExhaustiveOrderedUniquePairs,
2435 2,
2436 (I::Item, I::Item),
2437 exhaustive_ordered_unique_pairs,
2438 [0, 1]
2439);
2440
2441/// Defines lexicographic unique tuple generators.
2442///
2443/// Malachite provides [`lex_unique_pairs`], but you can also define `lex_unique_triples`,
2444/// `lex_unique_quadruples`, and so on, in your program using the code below. The documentation for
2445/// [`lex_unique_pairs`] describes these other functions as well.
2446///
2447/// See usage examples [here](self#lex_unique_pairs).
2448///
2449/// ```
2450/// use malachite_base::iterators::iterator_cache::IteratorCache;
2451/// use malachite_base::lex_unique_tuples;
2452/// use malachite_base::vecs::exhaustive::{unique_indices, UniqueIndices};
2453///
2454/// lex_unique_tuples!(
2455/// (pub(crate)),
2456/// LexUniqueTriples,
2457/// 3,
2458/// (I::Item, I::Item, I::Item),
2459/// lex_unique_triples,
2460/// [0, 1, 2]
2461/// );
2462/// lex_unique_tuples!(
2463/// (pub(crate)),
2464/// LexUniqueQuadruples,
2465/// 4,
2466/// (I::Item, I::Item, I::Item, I::Item),
2467/// lex_unique_quadruples,
2468/// [0, 1, 2, 3]
2469/// );
2470/// lex_unique_tuples!(
2471/// (pub(crate)),
2472/// LexUniqueQuintuples,
2473/// 5,
2474/// (I::Item, I::Item, I::Item, I::Item, I::Item),
2475/// lex_unique_quintuples,
2476/// [0, 1, 2, 3, 4]
2477/// );
2478/// lex_unique_tuples!(
2479/// (pub(crate)),
2480/// LexUniqueSextuples,
2481/// 6,
2482/// (I::Item, I::Item, I::Item, I::Item, I::Item, I::Item),
2483/// lex_unique_sextuples,
2484/// [0, 1, 2, 3, 4, 5]
2485/// );
2486/// lex_unique_tuples!(
2487/// (pub(crate)),
2488/// LexUniqueSeptuples,
2489/// 7,
2490/// (
2491/// I::Item,
2492/// I::Item,
2493/// I::Item,
2494/// I::Item,
2495/// I::Item,
2496/// I::Item,
2497/// I::Item
2498/// ),
2499/// lex_unique_septuples,
2500/// [0, 1, 2, 3, 4, 5, 6]
2501/// );
2502/// lex_unique_tuples!(
2503/// (pub(crate)),
2504/// LexUniqueOctuples,
2505/// 8,
2506/// (
2507/// I::Item,
2508/// I::Item,
2509/// I::Item,
2510/// I::Item,
2511/// I::Item,
2512/// I::Item,
2513/// I::Item,
2514/// I::Item
2515/// ),
2516/// lex_unique_octuples,
2517/// [0, 1, 2, 3, 4, 5, 6, 7]
2518/// );
2519/// ```
2520#[macro_export]
2521macro_rules! lex_unique_tuples {
2522 (
2523 ($($vis:tt)*),
2524 $struct: ident,
2525 $k: expr,
2526 $out_t: ty,
2527 $fn: ident,
2528 [$($i: expr),*]
2529 ) => {
2530 /// This documentation applies not only to `LexUniquePairs`, but also to `LexUniqueTriples`,
2531 /// `LexUniqueQuadruples`, and so on. See [`lex_unique_tuples`] for more information.
2532 ///
2533 /// Generates all $k$-tuples of elements from an iterator, where the tuples have no
2534 /// repetitions.
2535 ///
2536 /// The tuples are generated in lexicographic order with respect to the order of the element
2537 /// iterator.
2538 #[derive(Clone)]
2539 $($vis)* struct $struct<I: Iterator> where I::Item: Clone {
2540 first: bool,
2541 xs: IteratorCache<I>,
2542 indices: UniqueIndices,
2543 }
2544
2545 impl<I: Iterator> Iterator for $struct<I> where I::Item: Clone {
2546 type Item = $out_t;
2547
2548 fn next(&mut self) -> Option<Self::Item> {
2549 if self.first {
2550 let nonempty = !self.indices.used.is_empty();
2551 if nonempty && self.xs.get(self.indices.get_n() - 1).is_none() {
2552 self.indices.done = true;
2553 }
2554 self.first = false;
2555 }
2556 if self.xs.get(self.indices.get_n()).is_some() {
2557 self.indices.increment_n();
2558 }
2559 self.indices.next().map(|indices| {
2560 let mut results = indices.into_iter().map(|i| self.xs.assert_get(i).clone());
2561 ($(((results.next().unwrap(), $i).0)),*)
2562 })
2563 }
2564 }
2565
2566 /// This documentation applies not only to `lex_unique_pairs`, but also to
2567 /// `lex_unique_triples`, `lex_unique_quadruples`, and so on. See [`lex_unique_tuples`] for
2568 /// more information.
2569 ///
2570 /// Generates $k$-tuples of elements from a single iterator, such that each tuple has no
2571 /// repeated elements.
2572 ///
2573 /// The source iterator should not repeat any elements, but this is not enforced.
2574 ///
2575 /// The order is lexicographic with respect to the order of the element iterator.
2576 ///
2577 /// If the input iterator is infinite, the output length is also infinite.
2578 ///
2579 /// If the input iterator length is $n$, the output length is $\frac{n!}{k!}$.
2580 ///
2581 /// If `xs` is empty, the output is also empty.
2582 ///
2583 /// # Examples
2584 /// See [here](self#lex_unique_quadruples).
2585 #[inline]
2586 $($vis)* fn $fn<I: Iterator>(xs: I) -> $struct<I> where I::Item: Clone {
2587 $struct {
2588 first: true,
2589 xs: IteratorCache::new(xs),
2590 // Initial n is k, but will grow to reach actual n (or forever, if n is infinite)
2591 indices: unique_indices($k, $k),
2592 }
2593 }
2594 }
2595}
2596
2597lex_unique_tuples!(
2598 (pub),
2599 LexUniquePairs,
2600 2,
2601 (I::Item, I::Item),
2602 lex_unique_pairs,
2603 [0, 1]
2604);
2605
2606/// Generates all pairs of elements from an iterator, where the pairs have no repetitions.
2607///
2608/// This `struct` is created by [`exhaustive_unique_pairs`]; see its documentation for more.
2609#[derive(Clone)]
2610pub struct ExhaustiveUniquePairs<I: Iterator>
2611where
2612 I::Item: Clone,
2613{
2614 next: Option<(I::Item, I::Item)>,
2615 ps: ExhaustiveOrderedUniquePairs<I>,
2616}
2617
2618impl<I: Iterator> Iterator for ExhaustiveUniquePairs<I>
2619where
2620 I::Item: Clone,
2621{
2622 type Item = (I::Item, I::Item);
2623
2624 fn next(&mut self) -> Option<(I::Item, I::Item)> {
2625 if self.next.is_some() {
2626 take(&mut self.next)
2627 } else if let Some(p) = self.ps.next() {
2628 self.next = Some((p.1.clone(), p.0.clone()));
2629 Some(p)
2630 } else {
2631 None
2632 }
2633 }
2634}
2635
2636/// Generates pairs of elements from a single iterator, such that each pair has no repeated
2637/// elements.
2638///
2639/// The source iterator should not repeat any elements, but this is not enforced.
2640///
2641/// If the input iterator is infinite, the output length is also infinite.
2642///
2643/// If the input iterator length is $n$, the output length is $\tfrac{1}{2}{n!}$.
2644///
2645/// If `xs` is empty, the output is also empty.
2646///
2647/// # Examples
2648/// ```
2649/// use itertools::Itertools;
2650/// use malachite_base::tuples::exhaustive::exhaustive_unique_pairs;
2651///
2652/// let xss = exhaustive_unique_pairs(1..=6).take(20).collect_vec();
2653/// assert_eq!(
2654/// xss.into_iter().collect_vec().as_slice(),
2655/// &[
2656/// (1, 2),
2657/// (2, 1),
2658/// (1, 3),
2659/// (3, 1),
2660/// (2, 3),
2661/// (3, 2),
2662/// (1, 4),
2663/// (4, 1),
2664/// (2, 4),
2665/// (4, 2),
2666/// (3, 4),
2667/// (4, 3),
2668/// (1, 5),
2669/// (5, 1),
2670/// (2, 5),
2671/// (5, 2),
2672/// (3, 5),
2673/// (5, 3),
2674/// (4, 5),
2675/// (5, 4)
2676/// ]
2677/// );
2678/// ```
2679pub fn exhaustive_unique_pairs<I: Iterator>(xs: I) -> ExhaustiveUniquePairs<I>
2680where
2681 I::Item: Clone,
2682{
2683 ExhaustiveUniquePairs {
2684 next: None,
2685 ps: exhaustive_ordered_unique_pairs(xs),
2686 }
2687}
2688
2689/// Defines lexicographic unique tuple generators.
2690///
2691/// Malachite provides [`exhaustive_unique_pairs`], but you can also define
2692/// `exhaustive_unique_triples`, `lex_unique_quadruples`, and so on, in your program using the code
2693/// below.
2694///
2695/// See usage examples [here](self#lex_unique_quadruples).
2696///
2697/// ```
2698/// use malachite_base::exhaustive_unique_tuples;
2699/// use malachite_base::num::iterators::{ruler_sequence, RulerSequence};
2700/// use malachite_base::tuples::exhaustive::{
2701/// exhaustive_dependent_pairs, ExhaustiveDependentPairs,
2702/// };
2703/// use malachite_base::vecs::exhaustive::{
2704/// exhaustive_ordered_unique_vecs_fixed_length, ExhaustiveOrderedUniqueCollections,
2705/// ExhaustiveUniqueVecsGenerator,
2706/// };
2707/// use malachite_base::vecs::ExhaustiveVecPermutations;
2708///
2709/// exhaustive_unique_tuples!(
2710/// (pub(crate)),
2711/// ExhaustiveUniqueTriples,
2712/// 3,
2713/// (I::Item, I::Item, I::Item),
2714/// exhaustive_unique_triples,
2715/// [0, 1, 2]
2716/// );
2717/// exhaustive_unique_tuples!(
2718/// (pub(crate)),
2719/// ExhaustiveUniqueQuadruples,
2720/// 4,
2721/// (I::Item, I::Item, I::Item, I::Item),
2722/// exhaustive_unique_quadruples,
2723/// [0, 1, 2, 3]
2724/// );
2725/// exhaustive_unique_tuples!(
2726/// (pub(crate)),
2727/// ExhaustiveUniqueQuintuples,
2728/// 5,
2729/// (I::Item, I::Item, I::Item, I::Item, I::Item),
2730/// exhaustive_unique_quintuples,
2731/// [0, 1, 2, 3, 4]
2732/// );
2733/// exhaustive_unique_tuples!(
2734/// (pub(crate)),
2735/// ExhaustiveUniqueSextuples,
2736/// 6,
2737/// (I::Item, I::Item, I::Item, I::Item, I::Item, I::Item),
2738/// exhaustive_unique_sextuples,
2739/// [0, 1, 2, 3, 4, 5]
2740/// );
2741/// exhaustive_unique_tuples!(
2742/// (pub(crate)),
2743/// ExhaustiveUniqueSeptuples,
2744/// 7,
2745/// (
2746/// I::Item,
2747/// I::Item,
2748/// I::Item,
2749/// I::Item,
2750/// I::Item,
2751/// I::Item,
2752/// I::Item
2753/// ),
2754/// exhaustive_unique_septuples,
2755/// [0, 1, 2, 3, 4, 5, 6]
2756/// );
2757/// exhaustive_unique_tuples!(
2758/// (pub(crate)),
2759/// ExhaustiveUniqueOctuples,
2760/// 8,
2761/// (
2762/// I::Item,
2763/// I::Item,
2764/// I::Item,
2765/// I::Item,
2766/// I::Item,
2767/// I::Item,
2768/// I::Item,
2769/// I::Item
2770/// ),
2771/// exhaustive_unique_octuples,
2772/// [0, 1, 2, 3, 4, 5, 6, 7]
2773/// );
2774/// ```
2775#[macro_export]
2776macro_rules! exhaustive_unique_tuples {
2777 (
2778 ($($vis:tt)*),
2779 $struct: ident,
2780 $k: expr,
2781 $out_t: ty,
2782 $fn: ident,
2783 [$($i: expr),*]
2784 ) => {
2785 // Generates all $k$-tuples of elements from an iterator, where the tuples have no
2786 // repetitions.
2787 #[derive(Clone)]
2788 $($vis)* struct $struct<I: Iterator> where I::Item: Clone {
2789 xss: ExhaustiveDependentPairs<
2790 Vec<I::Item>,
2791 Vec<I::Item>,
2792 RulerSequence<usize>,
2793 ExhaustiveUniqueVecsGenerator<I::Item, I>,
2794 ExhaustiveOrderedUniqueCollections<I, Vec<I::Item>>,
2795 ExhaustiveVecPermutations<I::Item>,
2796 >
2797 }
2798
2799 impl<I: Iterator> Iterator for $struct<I> where I::Item: Clone {
2800 type Item = $out_t;
2801
2802 fn next(&mut self) -> Option<Self::Item> {
2803 self.xss.next().map(|mut p| {
2804 let mut drain = p.1.drain(..);
2805 ($(((drain.next().unwrap(), $i).0)),*)
2806 })
2807 }
2808 }
2809
2810 // Generates $k$-tuples of elements from a single iterator, such that each tuple has no
2811 // repeated elements.
2812 //
2813 // The source iterator should not repeat any elements, but this is not enforced.
2814 //
2815 // If the input iterator is infinite, the output length is also infinite.
2816 //
2817 // If the input iterator length is $n$, the output length is $\frac{n!}{k!}$.
2818 //
2819 // If `xs` is empty, the output is also empty.
2820 //
2821 // # Examples
2822 // See [here](self#exhaustive_unique_quadruples).
2823 $($vis)* fn $fn<I: Iterator>(xs: I) -> $struct<I> where I::Item: Clone {
2824 $struct {
2825 xss: exhaustive_dependent_pairs(
2826 ruler_sequence(),
2827 exhaustive_ordered_unique_vecs_fixed_length($k, xs),
2828 ExhaustiveUniqueVecsGenerator::new(),
2829 )
2830 }
2831 }
2832 }
2833}