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/// 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/// struct DPGeneratorFromMap<X: Clone + Eq + Hash, Y: 'static + Clone> {
2011/// map: HashMap<X, &'static [Y]>,
2012/// }
2013///
2014/// impl<X: Clone + Eq + Hash, Y: 'static + Clone>
2015/// ExhaustiveDependentPairsYsGenerator<X, Y, Cloned<Iter<'static, Y>>>
2016/// for DPGeneratorFromMap<X, Y>
2017/// {
2018/// #[inline]
2019/// fn get_ys(&self, x: &X) -> Cloned<Iter<'static, Y>> {
2020/// self.map[x].iter().cloned()
2021/// }
2022/// }
2023///
2024/// let xs = [1, 2, 3, 2, 3, 2, 2].iter().cloned();
2025/// let xss = exhaustive_dependent_pairs_stop_after_empty_ys(
2026/// ruler_sequence(),
2027/// xs,
2028/// DPGeneratorFromMap {
2029/// map: hashmap! {
2030/// 1 => &[100, 101, 102][..],
2031/// 2 => &[][..],
2032/// 3 => &[300, 301, 302][..]
2033/// },
2034/// },
2035/// )
2036/// .take(20)
2037/// .collect_vec();
2038/// assert_eq!(xss.as_slice(), &[(1, 100)]);
2039/// ```
2040#[inline]
2041pub const fn exhaustive_dependent_pairs_stop_after_empty_ys<
2042 X: Clone,
2043 Y,
2044 G: Iterator<Item = usize>,
2045 S: ExhaustiveDependentPairsYsGenerator<X, Y, J>,
2046 I: Iterator<Item = X>,
2047 J: Iterator<Item = Y>,
2048>(
2049 index_generator: G,
2050 xs: I,
2051 ys_generator: S,
2052) -> ExhaustiveDependentPairs<X, Y, G, S, I, J> {
2053 ExhaustiveDependentPairs {
2054 done: false,
2055 xs_done: false,
2056 stop_after_empty_ys: true,
2057 index_generator,
2058 xs,
2059 xs_yss: Vec::new(),
2060 ys_generator,
2061 }
2062}
2063
2064/// Defines lexicographic ordered unique tuple generators.
2065///
2066/// Malachite provides [`lex_ordered_unique_pairs`], but you can also define
2067/// `lex_ordered_unique_triples`, `lex_ordered_unique_quadruples`, and so on, in your program using
2068/// the code below. The documentation for [`lex_ordered_unique_pairs`] describes these other
2069/// functions as well.
2070///
2071/// See usage examples [here](self#lex_ordered_unique_quadruples).
2072///
2073/// ```
2074/// use malachite_base::iterators::iterator_cache::IteratorCache;
2075/// use malachite_base::lex_ordered_unique_tuples;
2076/// use malachite_base::vecs::exhaustive::fixed_length_ordered_unique_indices_helper;
2077/// use std::marker::PhantomData;
2078///
2079/// lex_ordered_unique_tuples!(
2080/// (pub(crate)),
2081/// LexOrderedUniqueTriples,
2082/// 3,
2083/// (I::Item, I::Item, I::Item),
2084/// lex_ordered_unique_triples,
2085/// [0, 1, 2]
2086/// );
2087/// lex_ordered_unique_tuples!(
2088/// (pub(crate)),
2089/// LexOrderedUniqueQuadruples,
2090/// 4,
2091/// (I::Item, I::Item, I::Item, I::Item),
2092/// lex_ordered_unique_quadruples,
2093/// [0, 1, 2, 3]
2094/// );
2095/// lex_ordered_unique_tuples!(
2096/// (pub(crate)),
2097/// LexOrderedUniqueQuintuples,
2098/// 5,
2099/// (I::Item, I::Item, I::Item, I::Item, I::Item),
2100/// lex_ordered_unique_quintuples,
2101/// [0, 1, 2, 3, 4]
2102/// );
2103/// lex_ordered_unique_tuples!(
2104/// (pub(crate)),
2105/// LexOrderedUniqueSextuples,
2106/// 6,
2107/// (I::Item, I::Item, I::Item, I::Item, I::Item, I::Item),
2108/// lex_ordered_unique_sextuples,
2109/// [0, 1, 2, 3, 4, 5]
2110/// );
2111/// lex_ordered_unique_tuples!(
2112/// (pub(crate)),
2113/// LexOrderedUniqueSeptuples,
2114/// 7,
2115/// (
2116/// I::Item,
2117/// I::Item,
2118/// I::Item,
2119/// I::Item,
2120/// I::Item,
2121/// I::Item,
2122/// I::Item
2123/// ),
2124/// lex_ordered_unique_septuples,
2125/// [0, 1, 2, 3, 4, 5, 6]
2126/// );
2127/// lex_ordered_unique_tuples!(
2128/// (pub(crate)),
2129/// LexOrderedUniqueOctuples,
2130/// 8,
2131/// (
2132/// I::Item,
2133/// I::Item,
2134/// I::Item,
2135/// I::Item,
2136/// I::Item,
2137/// I::Item,
2138/// I::Item,
2139/// I::Item
2140/// ),
2141/// lex_ordered_unique_octuples,
2142/// [0, 1, 2, 3, 4, 5, 6, 7]
2143/// );
2144/// ```
2145#[macro_export]
2146macro_rules! lex_ordered_unique_tuples {
2147 (
2148 ($($vis:tt)*),
2149 $struct: ident,
2150 $k: expr,
2151 $out_t: ty,
2152 $fn: ident,
2153 [$($i: expr),*]
2154 ) => {
2155 /// This documentation applies not only to `LexOrderedUniquePairs`, but also to
2156 /// `LexOrderedUniqueTriples`, `LexOrderedUniqueQuadruples`, and so on. See
2157 /// [`lex_ordered_unique_tuples`] for more information.
2158 ///
2159 /// Generates all $k$-tuples of elements from an iterator, where the tuples have no
2160 /// repetitions and are ordered the same way as in the iterator.
2161 ///
2162 /// The tuples are generated in lexicographic order with respect to the order of the element
2163 /// iterator.
2164 #[derive(Clone, Debug)]
2165 $($vis)* struct $struct<I: Iterator> where I::Item: Clone {
2166 first: bool,
2167 done: bool,
2168 xs: IteratorCache<I>,
2169 indices: [usize; $k],
2170 phantom: PhantomData<*const I::Item>,
2171 }
2172
2173 impl<I: Iterator> Iterator for $struct<I> where I::Item: Clone {
2174 type Item = $out_t;
2175
2176 fn next(&mut self) -> Option<Self::Item> {
2177 if self.done {
2178 return None;
2179 }
2180 if self.first {
2181 self.first = false;
2182 self.xs.get($k);
2183 if let Some(n) = self.xs.known_len() {
2184 if n < $k {
2185 self.done = true;
2186 return None;
2187 }
2188 }
2189 } else {
2190 if let Some(n) = self.xs.known_len() {
2191 if fixed_length_ordered_unique_indices_helper(n, $k, &mut self.indices) {
2192 self.done = true;
2193 return None;
2194 }
2195 } else {
2196 *self.indices.last_mut().unwrap() += 1;
2197 }
2198 }
2199 if let Some(&last_index) = self.indices.last() {
2200 // Give known len a chance to be set
2201 self.xs.get(last_index + 1);
2202 }
2203 Some(($(self.xs.assert_get(self.indices[$i]).clone(),)*))
2204 }
2205 }
2206
2207 /// This documentation applies not only to `lex_ordered_unique_pairs`, but also to
2208 /// `lex_ordered_unique_triples`, `lex_ordered_unique_quadruples`, and so on. See
2209 /// [`lex_ordered_unique_tuples`] for more information.
2210 ///
2211 /// Generates $k$-tuples of elements from a single iterator, such that each tuple has no
2212 /// repeated elements, and the elements in each [`Vec`] are ordered the same way as they are
2213 /// in the source iterator.
2214 ///
2215 /// The source iterator should not repeat any elements, but this is not enforced.
2216 ///
2217 /// The order is lexicographic with respect to the order of the element iterator.
2218 ///
2219 /// If the input iterator is infinite, the output length is also infinite.
2220 ///
2221 /// If the input iterator length is $n$, the output length is $\binom{n}{k}$.
2222 ///
2223 /// If `xs` is empty, the output is also empty.
2224 ///
2225 /// # Examples
2226 /// See [here](self#lex_ordered_unique_quadruples).
2227 $($vis)* const fn $fn<I: Iterator>(xs: I) -> $struct<I> where I::Item: Clone {
2228 $struct {
2229 first: true,
2230 done: false,
2231 xs: IteratorCache::new(xs),
2232 indices: [$($i),*],
2233 phantom: PhantomData,
2234 }
2235 }
2236 }
2237}
2238
2239lex_ordered_unique_tuples!(
2240 (pub),
2241 LexOrderedUniquePairs,
2242 2,
2243 (I::Item, I::Item),
2244 lex_ordered_unique_pairs,
2245 [0, 1]
2246);
2247
2248/// Defines exhaustive ordered unique tuple generators.
2249///
2250/// Malachite provides [`exhaustive_ordered_unique_pairs`], but you can also define
2251/// `exhaustive_ordered_unique_triples`, `exhaustive_ordered_unique_quadruples`, and so on, in your
2252/// program using the code below. The documentation for [`exhaustive_ordered_unique_pairs`]
2253/// describes these other functions as well.
2254///
2255/// See usage examples [here](self#exhaustive_ordered_unique_quadruples).
2256///
2257/// ```
2258/// use malachite_base::exhaustive_ordered_unique_tuples;
2259/// use malachite_base::iterators::iterator_cache::IteratorCache;
2260/// use malachite_base::vecs::exhaustive::next_bit_pattern;
2261///
2262/// exhaustive_ordered_unique_tuples!(
2263/// (pub(crate)),
2264/// ExhaustiveOrderedUniqueTriples,
2265/// 3,
2266/// (I::Item, I::Item, I::Item),
2267/// exhaustive_ordered_unique_triples,
2268/// [0, 1, 2]
2269/// );
2270/// exhaustive_ordered_unique_tuples!(
2271/// (pub(crate)),
2272/// ExhaustiveOrderedUniqueQuadruples,
2273/// 4,
2274/// (I::Item, I::Item, I::Item, I::Item),
2275/// exhaustive_ordered_unique_quadruples,
2276/// [0, 1, 2, 3]
2277/// );
2278/// exhaustive_ordered_unique_tuples!(
2279/// (pub(crate)),
2280/// ExhaustiveOrderedUniqueQuintuples,
2281/// 5,
2282/// (I::Item, I::Item, I::Item, I::Item, I::Item),
2283/// exhaustive_ordered_unique_quintuples,
2284/// [0, 1, 2, 3, 4]
2285/// );
2286/// exhaustive_ordered_unique_tuples!(
2287/// (pub(crate)),
2288/// ExhaustiveOrderedUniqueSextuples,
2289/// 6,
2290/// (I::Item, I::Item, I::Item, I::Item, I::Item, I::Item),
2291/// exhaustive_ordered_unique_sextuples,
2292/// [0, 1, 2, 3, 4, 5]
2293/// );
2294/// exhaustive_ordered_unique_tuples!(
2295/// (pub(crate)),
2296/// ExhaustiveOrderedUniqueSeptuples,
2297/// 7,
2298/// (
2299/// I::Item,
2300/// I::Item,
2301/// I::Item,
2302/// I::Item,
2303/// I::Item,
2304/// I::Item,
2305/// I::Item
2306/// ),
2307/// exhaustive_ordered_unique_septuples,
2308/// [0, 1, 2, 3, 4, 5, 6]
2309/// );
2310/// exhaustive_ordered_unique_tuples!(
2311/// (pub(crate)),
2312/// ExhaustiveOrderedUniqueOctuples,
2313/// 8,
2314/// (
2315/// I::Item,
2316/// I::Item,
2317/// I::Item,
2318/// I::Item,
2319/// I::Item,
2320/// I::Item,
2321/// I::Item,
2322/// I::Item
2323/// ),
2324/// exhaustive_ordered_unique_octuples,
2325/// [0, 1, 2, 3, 4, 5, 6, 7]
2326/// );
2327/// ```
2328#[macro_export]
2329macro_rules! exhaustive_ordered_unique_tuples {
2330 (
2331 ($($vis:tt)*),
2332 $struct: ident,
2333 $k: expr,
2334 $out_t: ty,
2335 $fn: ident,
2336 [$($i: expr),*]
2337 ) => {
2338 /// This documentation applies not only to `ExhaustiveOrderedUniquePairs`, but also to
2339 /// `ExhaustiveOrderedUniqueTriples`, `ExhaustiveOrderedUniqueQuadruples`, and so on. See
2340 /// [`exhaustive_ordered_unique_tuples`] for more information.
2341 ///
2342 /// Generates all $k$-tuples of elements from an iterator, where the tuples have no
2343 /// repetitions and are ordered the same way as in the iterator.
2344 #[derive(Clone)]
2345 pub struct $struct<I: Iterator>
2346 where
2347 I::Item: Clone,
2348 {
2349 done: bool,
2350 first: bool,
2351 xs: IteratorCache<I>,
2352 pattern: Vec<bool>,
2353 }
2354
2355 impl<I: Iterator> Iterator for $struct<I>
2356 where
2357 I::Item: Clone,
2358 {
2359 type Item = $out_t;
2360
2361 fn next(&mut self) -> Option<Self::Item> {
2362 if self.done {
2363 return None;
2364 } else if self.first {
2365 self.first = false;
2366 } else {
2367 let mut c = $k;
2368 next_bit_pattern(&mut self.pattern, &mut c, $k, $k);
2369 }
2370 if !self.pattern.is_empty() && self.xs.get(self.pattern.len() - 1).is_none() {
2371 self.done = true;
2372 return None;
2373 }
2374 let mut results = self.pattern.iter().enumerate().filter_map(|(i, &b)| {
2375 if b {
2376 Some(self.xs.assert_get(i).clone())
2377 } else {
2378 None
2379 }
2380 });
2381 Some(($(((results.next().unwrap(), $i).0)),*))
2382 }
2383 }
2384
2385 /// This documentation applies not only to `exhaustive_ordered_unique_pairs`, but also to
2386 /// `exhaustive_ordered_unique_triples`, `exhaustive_ordered_unique_quadruples`, and so on.
2387 /// See [`exhaustive_ordered_unique_tuples`] for more information.
2388 ///
2389 /// Generates $k$-tuples of elements from a single iterator, such that each tuple has no
2390 /// repeated elements, and the elements in each [`Vec`] are ordered the same way as they are
2391 /// in the source iterator.
2392 ///
2393 /// The source iterator should not repeat any elements, but this is not enforced.
2394 ///
2395 /// If the input iterator is infinite, the output length is also infinite.
2396 ///
2397 /// If the input iterator length is $n$, the output length is $\binom{n}{k}$.
2398 ///
2399 /// If `xs` is empty, the output is also empty.
2400 ///
2401 /// # Examples
2402 /// See [here](self#exhaustive_ordered_unique_quadruples).
2403 pub fn $fn<I: Iterator>(xs: I) -> $struct<I>
2404 where
2405 I::Item: Clone,
2406 {
2407 $struct {
2408 done: false,
2409 first: true,
2410 xs: IteratorCache::new(xs),
2411 pattern: vec![true; $k],
2412 }
2413 }
2414 }
2415}
2416exhaustive_ordered_unique_tuples!(
2417 (pub),
2418 ExhaustiveOrderedUniquePairs,
2419 2,
2420 (I::Item, I::Item),
2421 exhaustive_ordered_unique_pairs,
2422 [0, 1]
2423);
2424
2425/// Defines lexicographic unique tuple generators.
2426///
2427/// Malachite provides [`lex_unique_pairs`], but you can also define `lex_unique_triples`,
2428/// `lex_unique_quadruples`, and so on, in your program using the code below. The documentation for
2429/// [`lex_unique_pairs`] describes these other functions as well.
2430///
2431/// See usage examples [here](self#lex_unique_pairs).
2432///
2433/// ```
2434/// use malachite_base::iterators::iterator_cache::IteratorCache;
2435/// use malachite_base::lex_unique_tuples;
2436/// use malachite_base::vecs::exhaustive::{unique_indices, UniqueIndices};
2437///
2438/// lex_unique_tuples!(
2439/// (pub(crate)),
2440/// LexUniqueTriples,
2441/// 3,
2442/// (I::Item, I::Item, I::Item),
2443/// lex_unique_triples,
2444/// [0, 1, 2]
2445/// );
2446/// lex_unique_tuples!(
2447/// (pub(crate)),
2448/// LexUniqueQuadruples,
2449/// 4,
2450/// (I::Item, I::Item, I::Item, I::Item),
2451/// lex_unique_quadruples,
2452/// [0, 1, 2, 3]
2453/// );
2454/// lex_unique_tuples!(
2455/// (pub(crate)),
2456/// LexUniqueQuintuples,
2457/// 5,
2458/// (I::Item, I::Item, I::Item, I::Item, I::Item),
2459/// lex_unique_quintuples,
2460/// [0, 1, 2, 3, 4]
2461/// );
2462/// lex_unique_tuples!(
2463/// (pub(crate)),
2464/// LexUniqueSextuples,
2465/// 6,
2466/// (I::Item, I::Item, I::Item, I::Item, I::Item, I::Item),
2467/// lex_unique_sextuples,
2468/// [0, 1, 2, 3, 4, 5]
2469/// );
2470/// lex_unique_tuples!(
2471/// (pub(crate)),
2472/// LexUniqueSeptuples,
2473/// 7,
2474/// (
2475/// I::Item,
2476/// I::Item,
2477/// I::Item,
2478/// I::Item,
2479/// I::Item,
2480/// I::Item,
2481/// I::Item
2482/// ),
2483/// lex_unique_septuples,
2484/// [0, 1, 2, 3, 4, 5, 6]
2485/// );
2486/// lex_unique_tuples!(
2487/// (pub(crate)),
2488/// LexUniqueOctuples,
2489/// 8,
2490/// (
2491/// I::Item,
2492/// I::Item,
2493/// I::Item,
2494/// I::Item,
2495/// I::Item,
2496/// I::Item,
2497/// I::Item,
2498/// I::Item
2499/// ),
2500/// lex_unique_octuples,
2501/// [0, 1, 2, 3, 4, 5, 6, 7]
2502/// );
2503/// ```
2504#[macro_export]
2505macro_rules! lex_unique_tuples {
2506 (
2507 ($($vis:tt)*),
2508 $struct: ident,
2509 $k: expr,
2510 $out_t: ty,
2511 $fn: ident,
2512 [$($i: expr),*]
2513 ) => {
2514 /// This documentation applies not only to `LexUniquePairs`, but also to `LexUniqueTriples`,
2515 /// `LexUniqueQuadruples`, and so on. See [`lex_unique_tuples`] for more information.
2516 ///
2517 /// Generates all $k$-tuples of elements from an iterator, where the tuples have no
2518 /// repetitions.
2519 ///
2520 /// The tuples are generated in lexicographic order with respect to the order of the element
2521 /// iterator.
2522 #[derive(Clone)]
2523 $($vis)* struct $struct<I: Iterator> where I::Item: Clone {
2524 first: bool,
2525 xs: IteratorCache<I>,
2526 indices: UniqueIndices,
2527 }
2528
2529 impl<I: Iterator> Iterator for $struct<I> where I::Item: Clone {
2530 type Item = $out_t;
2531
2532 fn next(&mut self) -> Option<Self::Item> {
2533 if self.first {
2534 let nonempty = !self.indices.used.is_empty();
2535 if nonempty && self.xs.get(self.indices.get_n() - 1).is_none() {
2536 self.indices.done = true;
2537 }
2538 self.first = false;
2539 }
2540 if self.xs.get(self.indices.get_n()).is_some() {
2541 self.indices.increment_n();
2542 }
2543 self.indices.next().map(|indices| {
2544 let mut results = indices.into_iter().map(|i| self.xs.assert_get(i).clone());
2545 ($(((results.next().unwrap(), $i).0)),*)
2546 })
2547 }
2548 }
2549
2550 /// This documentation applies not only to `lex_unique_pairs`, but also to
2551 /// `lex_unique_triples`, `lex_unique_quadruples`, and so on. See [`lex_unique_tuples`] for
2552 /// more information.
2553 ///
2554 /// Generates $k$-tuples of elements from a single iterator, such that each tuple has no
2555 /// repeated elements.
2556 ///
2557 /// The source iterator should not repeat any elements, but this is not enforced.
2558 ///
2559 /// The order is lexicographic with respect to the order of the element iterator.
2560 ///
2561 /// If the input iterator is infinite, the output length is also infinite.
2562 ///
2563 /// If the input iterator length is $n$, the output length is $\frac{n!}{k!}$.
2564 ///
2565 /// If `xs` is empty, the output is also empty.
2566 ///
2567 /// # Examples
2568 /// See [here](self#lex_unique_quadruples).
2569 #[inline]
2570 $($vis)* fn $fn<I: Iterator>(xs: I) -> $struct<I> where I::Item: Clone {
2571 $struct {
2572 first: true,
2573 xs: IteratorCache::new(xs),
2574 // Initial n is k, but will grow to reach actual n (or forever, if n is infinite)
2575 indices: unique_indices($k, $k),
2576 }
2577 }
2578 }
2579}
2580
2581lex_unique_tuples!(
2582 (pub),
2583 LexUniquePairs,
2584 2,
2585 (I::Item, I::Item),
2586 lex_unique_pairs,
2587 [0, 1]
2588);
2589
2590/// Generates all pairs of elements from an iterator, where the pairs have no repetitions.
2591///
2592/// This `struct` is created by [`exhaustive_unique_pairs`]; see its documentation for more.
2593#[derive(Clone)]
2594pub struct ExhaustiveUniquePairs<I: Iterator>
2595where
2596 I::Item: Clone,
2597{
2598 next: Option<(I::Item, I::Item)>,
2599 ps: ExhaustiveOrderedUniquePairs<I>,
2600}
2601
2602impl<I: Iterator> Iterator for ExhaustiveUniquePairs<I>
2603where
2604 I::Item: Clone,
2605{
2606 type Item = (I::Item, I::Item);
2607
2608 fn next(&mut self) -> Option<(I::Item, I::Item)> {
2609 if self.next.is_some() {
2610 take(&mut self.next)
2611 } else if let Some(p) = self.ps.next() {
2612 self.next = Some((p.1.clone(), p.0.clone()));
2613 Some(p)
2614 } else {
2615 None
2616 }
2617 }
2618}
2619
2620/// Generates pairs of elements from a single iterator, such that each pair has no repeated
2621/// elements.
2622///
2623/// The source iterator should not repeat any elements, but this is not enforced.
2624///
2625/// If the input iterator is infinite, the output length is also infinite.
2626///
2627/// If the input iterator length is $n$, the output length is $\tfrac{1}{2}{n!}$.
2628///
2629/// If `xs` is empty, the output is also empty.
2630///
2631/// # Examples
2632/// ```
2633/// use itertools::Itertools;
2634/// use malachite_base::tuples::exhaustive::exhaustive_unique_pairs;
2635///
2636/// let xss = exhaustive_unique_pairs(1..=6).take(20).collect_vec();
2637/// assert_eq!(
2638/// xss.into_iter().collect_vec().as_slice(),
2639/// &[
2640/// (1, 2),
2641/// (2, 1),
2642/// (1, 3),
2643/// (3, 1),
2644/// (2, 3),
2645/// (3, 2),
2646/// (1, 4),
2647/// (4, 1),
2648/// (2, 4),
2649/// (4, 2),
2650/// (3, 4),
2651/// (4, 3),
2652/// (1, 5),
2653/// (5, 1),
2654/// (2, 5),
2655/// (5, 2),
2656/// (3, 5),
2657/// (5, 3),
2658/// (4, 5),
2659/// (5, 4)
2660/// ]
2661/// );
2662/// ```
2663pub fn exhaustive_unique_pairs<I: Iterator>(xs: I) -> ExhaustiveUniquePairs<I>
2664where
2665 I::Item: Clone,
2666{
2667 ExhaustiveUniquePairs {
2668 next: None,
2669 ps: exhaustive_ordered_unique_pairs(xs),
2670 }
2671}
2672
2673/// Defines lexicographic unique tuple generators.
2674///
2675/// Malachite provides [`exhaustive_unique_pairs`], but you can also define
2676/// `exhaustive_unique_triples`, `lex_unique_quadruples`, and so on, in your program using the code
2677/// below.
2678///
2679/// See usage examples [here](self#lex_unique_quadruples).
2680///
2681/// ```
2682/// use malachite_base::exhaustive_unique_tuples;
2683/// use malachite_base::num::iterators::{ruler_sequence, RulerSequence};
2684/// use malachite_base::tuples::exhaustive::{
2685/// exhaustive_dependent_pairs, ExhaustiveDependentPairs,
2686/// };
2687/// use malachite_base::vecs::exhaustive::{
2688/// exhaustive_ordered_unique_vecs_fixed_length, ExhaustiveOrderedUniqueCollections,
2689/// ExhaustiveUniqueVecsGenerator,
2690/// };
2691/// use malachite_base::vecs::ExhaustiveVecPermutations;
2692///
2693/// exhaustive_unique_tuples!(
2694/// (pub(crate)),
2695/// ExhaustiveUniqueTriples,
2696/// 3,
2697/// (I::Item, I::Item, I::Item),
2698/// exhaustive_unique_triples,
2699/// [0, 1, 2]
2700/// );
2701/// exhaustive_unique_tuples!(
2702/// (pub(crate)),
2703/// ExhaustiveUniqueQuadruples,
2704/// 4,
2705/// (I::Item, I::Item, I::Item, I::Item),
2706/// exhaustive_unique_quadruples,
2707/// [0, 1, 2, 3]
2708/// );
2709/// exhaustive_unique_tuples!(
2710/// (pub(crate)),
2711/// ExhaustiveUniqueQuintuples,
2712/// 5,
2713/// (I::Item, I::Item, I::Item, I::Item, I::Item),
2714/// exhaustive_unique_quintuples,
2715/// [0, 1, 2, 3, 4]
2716/// );
2717/// exhaustive_unique_tuples!(
2718/// (pub(crate)),
2719/// ExhaustiveUniqueSextuples,
2720/// 6,
2721/// (I::Item, I::Item, I::Item, I::Item, I::Item, I::Item),
2722/// exhaustive_unique_sextuples,
2723/// [0, 1, 2, 3, 4, 5]
2724/// );
2725/// exhaustive_unique_tuples!(
2726/// (pub(crate)),
2727/// ExhaustiveUniqueSeptuples,
2728/// 7,
2729/// (
2730/// I::Item,
2731/// I::Item,
2732/// I::Item,
2733/// I::Item,
2734/// I::Item,
2735/// I::Item,
2736/// I::Item
2737/// ),
2738/// exhaustive_unique_septuples,
2739/// [0, 1, 2, 3, 4, 5, 6]
2740/// );
2741/// exhaustive_unique_tuples!(
2742/// (pub(crate)),
2743/// ExhaustiveUniqueOctuples,
2744/// 8,
2745/// (
2746/// I::Item,
2747/// I::Item,
2748/// I::Item,
2749/// I::Item,
2750/// I::Item,
2751/// I::Item,
2752/// I::Item,
2753/// I::Item
2754/// ),
2755/// exhaustive_unique_octuples,
2756/// [0, 1, 2, 3, 4, 5, 6, 7]
2757/// );
2758/// ```
2759#[macro_export]
2760macro_rules! exhaustive_unique_tuples {
2761 (
2762 ($($vis:tt)*),
2763 $struct: ident,
2764 $k: expr,
2765 $out_t: ty,
2766 $fn: ident,
2767 [$($i: expr),*]
2768 ) => {
2769 // Generates all $k$-tuples of elements from an iterator, where the tuples have no
2770 // repetitions.
2771 #[derive(Clone)]
2772 $($vis)* struct $struct<I: Iterator> where I::Item: Clone {
2773 xss: ExhaustiveDependentPairs<
2774 Vec<I::Item>,
2775 Vec<I::Item>,
2776 RulerSequence<usize>,
2777 ExhaustiveUniqueVecsGenerator<I::Item, I>,
2778 ExhaustiveOrderedUniqueCollections<I, Vec<I::Item>>,
2779 ExhaustiveVecPermutations<I::Item>,
2780 >
2781 }
2782
2783 impl<I: Iterator> Iterator for $struct<I> where I::Item: Clone {
2784 type Item = $out_t;
2785
2786 fn next(&mut self) -> Option<Self::Item> {
2787 self.xss.next().map(|mut p| {
2788 let mut drain = p.1.drain(..);
2789 ($(((drain.next().unwrap(), $i).0)),*)
2790 })
2791 }
2792 }
2793
2794 // Generates $k$-tuples of elements from a single iterator, such that each tuple has no
2795 // repeated elements.
2796 //
2797 // The source iterator should not repeat any elements, but this is not enforced.
2798 //
2799 // If the input iterator is infinite, the output length is also infinite.
2800 //
2801 // If the input iterator length is $n$, the output length is $\frac{n!}{k!}$.
2802 //
2803 // If `xs` is empty, the output is also empty.
2804 //
2805 // # Examples
2806 // See [here](self#exhaustive_unique_quadruples).
2807 $($vis)* fn $fn<I: Iterator>(xs: I) -> $struct<I> where I::Item: Clone {
2808 $struct {
2809 xss: exhaustive_dependent_pairs(
2810 ruler_sequence(),
2811 exhaustive_ordered_unique_vecs_fixed_length($k, xs),
2812 ExhaustiveUniqueVecsGenerator::new(),
2813 )
2814 }
2815 }
2816 }
2817}