Skip to main content

malachite_base/vecs/
random.rs

1// Copyright © 2026 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::num::conversion::traits::ExactFrom;
10use crate::num::random::geometric::{
11    GeometricRandomNaturalValues, geometric_random_unsigned_inclusive_range,
12    geometric_random_unsigneds,
13};
14use crate::num::random::{
15    RandomUnsignedInclusiveRange, RandomUnsignedRange, random_unsigned_inclusive_range,
16    random_unsigned_range,
17};
18use crate::random::Seed;
19use crate::sets::random::{
20    RandomBTreeSets, RandomBTreeSetsFixedLength, random_b_tree_sets_fixed_length,
21    random_b_tree_sets_from_length_iterator,
22};
23use crate::vecs::exhaustive::validate_oi_map;
24use std::cmp::Ordering::*;
25use std::collections::HashMap;
26use std::hash::Hash;
27use std::iter::{Repeat, repeat};
28
29/// Generates random [`Vec`]s of a given length using elements from a single iterator.
30///
31/// This `struct` is created by [`random_vecs_fixed_length_from_single`]; see its documentation for
32/// more.
33#[derive(Clone, Debug)]
34pub struct RandomFixedLengthVecsFromSingle<I: Iterator> {
35    len: u64,
36    xs: I,
37}
38
39impl<I: Iterator> Iterator for RandomFixedLengthVecsFromSingle<I> {
40    type Item = Vec<I::Item>;
41
42    #[inline]
43    fn next(&mut self) -> Option<Vec<I::Item>> {
44        Some((&mut self.xs).take(usize::exact_from(self.len)).collect())
45    }
46}
47
48/// Randomly generates [`Vec`]s of a given length using elements from a single iterator.
49///
50/// The probability of a particular length-$n$ [`Vec`] being generated is the product of the
51/// probabilities of each of its elements.
52///
53/// If `len` is 0, the output consists of the empty list, repeated.
54///
55/// `xs` must be infinite.
56///
57/// # Worst-case complexity per iteration
58/// $T(i) = O(\ell T^\prime(i))$
59///
60/// $M(i) = O(\ell M^\prime(i))$
61///
62/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
63/// $M^\prime$ are the time and memory functions of `xs`, and $\ell$ is `len`.
64///
65/// # Expected complexity per iteration
66/// $T(i) = O(m T^\prime(i))$
67///
68/// $M(i) = O(m M^\prime(i))$
69///
70/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
71/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`, and $m$ is
72/// `mean_length_numerator / mean_length_denominator`.
73///
74/// # Examples
75/// ```
76/// use itertools::Itertools;
77/// use malachite_base::num::random::random_unsigned_inclusive_range;
78/// use malachite_base::random::EXAMPLE_SEED;
79/// use malachite_base::vecs::random::random_vecs_fixed_length_from_single;
80///
81/// let xss = random_vecs_fixed_length_from_single(
82///     2,
83///     random_unsigned_inclusive_range::<u32>(EXAMPLE_SEED, 1, 100),
84/// )
85/// .take(10)
86/// .collect_vec();
87/// assert_eq!(
88///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
89///     &[
90///         &[95, 24],
91///         &[99, 71],
92///         &[93, 53],
93///         &[85, 34],
94///         &[48, 2],
95///         &[55, 11],
96///         &[48, 18],
97///         &[90, 93],
98///         &[67, 93],
99///         &[93, 95]
100///     ]
101/// );
102/// ```
103#[inline]
104pub const fn random_vecs_fixed_length_from_single<I: Iterator>(
105    len: u64,
106    xs: I,
107) -> RandomFixedLengthVecsFromSingle<I> {
108    RandomFixedLengthVecsFromSingle { len, xs }
109}
110
111/// Defines random fixed-length [`Vec`] generators.
112///
113/// Malachite provides [`random_vecs_length_2`] and [`random_vecs_fixed_length_2_inputs`], but you
114/// can also define `random_vecs_length_3`, `random_vecs_length_4`, and so on, and
115/// `random_vecs_fixed_length_3_inputs`, `random_vecs_fixed_length_4_inputs`, and so on, in your
116/// program using the code below. The documentation for [`random_vecs_length_2`] and
117/// [`random_vecs_fixed_length_2_inputs`] describes these other functions as well.
118///
119/// See usage examples [here](self#lex_vecs_length_2) and
120/// [here](self#random_vecs_fixed_length_2_inputs).
121///
122/// ```
123/// use malachite_base::random::Seed;
124/// use malachite_base::random_vecs_fixed_length;
125/// use malachite_base::vecs::exhaustive::validate_oi_map;
126///
127/// random_vecs_fixed_length!(
128///     (pub(crate)),
129///     RandomFixedLengthVecs3Inputs,
130///     random_vecs_fixed_length_3_inputs,
131///     random_vecs_length_3,
132///     [0, I, xs, xs_gen],
133///     [1, J, ys, ys_gen],
134///     [2, K, zs, zs_gen]
135/// );
136/// random_vecs_fixed_length!(
137///     (pub(crate)),
138///     RandomFixedLengthVecs4Inputs,
139///     random_vecs_fixed_length_4_inputs,
140///     random_vecs_length_4,
141///     [0, I, xs, xs_gen],
142///     [1, J, ys, ys_gen],
143///     [2, K, zs, zs_gen],
144///     [3, L, ws, ws_gen]
145/// );
146/// random_vecs_fixed_length!(
147///     (pub(crate)),
148///     RandomFixedLengthVecs5Inputs,
149///     random_vecs_fixed_length_5_inputs,
150///     random_vecs_length_5,
151///     [0, I, xs, xs_gen],
152///     [1, J, ys, ys_gen],
153///     [2, K, zs, zs_gen],
154///     [3, L, ws, ws_gen],
155///     [4, M, vs, vs_gen]
156/// );
157/// random_vecs_fixed_length!(
158///     (pub(crate)),
159///     RandomFixedLengthVecs6Inputs,
160///     random_vecs_fixed_length_6_inputs,
161///     random_vecs_length_6,
162///     [0, I, xs, xs_gen],
163///     [1, J, ys, ys_gen],
164///     [2, K, zs, zs_gen],
165///     [3, L, ws, ws_gen],
166///     [4, M, vs, vs_gen],
167///     [5, N, us, us_gen]
168/// );
169/// random_vecs_fixed_length!(
170///     (pub(crate)),
171///     RandomFixedLengthVecs7Inputs,
172///     random_vecs_fixed_length_7_inputs,
173///     random_vecs_length_7,
174///     [0, I, xs, xs_gen],
175///     [1, J, ys, ys_gen],
176///     [2, K, zs, zs_gen],
177///     [3, L, ws, ws_gen],
178///     [4, M, vs, vs_gen],
179///     [5, N, us, us_gen],
180///     [6, O, ts, ts_gen]
181/// );
182/// random_vecs_fixed_length!(
183///     (pub(crate)),
184///     RandomFixedLengthVecs8Inputs,
185///     random_vecs_fixed_length_8_inputs,
186///     random_vecs_length_8,
187///     [0, I, xs, xs_gen],
188///     [1, J, ys, ys_gen],
189///     [2, K, zs, zs_gen],
190///     [3, L, ws, ws_gen],
191///     [4, M, vs, vs_gen],
192///     [5, N, us, us_gen],
193///     [6, O, ts, ts_gen],
194///     [7, P, ss, ss_gen]
195/// );
196/// ```
197#[macro_export]
198macro_rules! random_vecs_fixed_length {
199    (
200        ($($vis:tt)*),
201        $random_struct: ident,
202        $random_fn: ident,
203        $random_1_to_1_fn: ident,
204        $([$i: expr, $it: ident, $xs: ident, $xs_gen: ident]),*
205    ) => {
206        /// This documentation applies not only to `RandomFixedLengthVecs2Inputs`, but also to
207        /// `RandomFixedLengthVecs3Inputs`, `RandomFixedLengthVecs4Inputs`, and so on. See
208        /// [`random_vecs_fixed_length`] for more information.
209        ///
210        /// Generates random [`Vec`]s of a given length using elements from $m$ iterators.
211        ///
212        /// The fixed length $n$ of the [`Vec`]s is greater than or equal to $m$.
213        #[derive(Clone, Debug)]
214        $($vis)* struct $random_struct<T, $($it: Iterator<Item = T>),*> {
215            $($xs: $it,)*
216            output_to_input_map: Vec<usize>,
217        }
218
219        impl<T, $($it: Iterator<Item = T>),*> Iterator
220            for $random_struct<T, $($it),*>
221        {
222            type Item = Vec<T>;
223
224            #[inline]
225            fn next(&mut self) -> Option<Vec<T>> {
226                let mut out = Vec::with_capacity(self.output_to_input_map.len());
227                for &i in &self.output_to_input_map {
228                    out.push(
229                        match i {
230                            $(
231                                $i => self.$xs.next(),
232                            )*
233                            _ => unreachable!(),
234                        }
235                        .unwrap(),
236                    );
237                }
238                Some(out)
239            }
240        }
241
242        /// This documentation applies not only to `random_vecs_fixed_length_2_inputs`, but also to
243        /// `random_vecs_fixed_length_3_inputs`, `random_vecs_fixed_length_4_inputs`, and so on. See
244        /// [`random_vecs_fixed_length`] for more information.
245        ///
246        /// Generates random length-$n$ [`Vec`]s using elements from $m$ iterators, where $m \leq
247        /// n$.
248        ///
249        /// The `output_to_input_map` parameter defines which iterators are mapped to which slot in
250        /// the output [`Vec`]s. The length of the output [`Vec`]s, $n$, is specified by the length
251        /// of `output_to_input_map`.
252        ///
253        /// The $i$th element of `output_to_input_map` is an index from 0 to $m-1$ which specifies
254        /// which iterator the $i$th output slot is populated with. Together, the elements must
255        /// include all indices from 0 to $m-1$, inclusive, possibly with repetitions.
256        ///
257        /// `xs` must be infinite.
258        ///
259        /// # Examples
260        /// See [here](self#random_vecs_fixed_length_2_inputs).
261        #[allow(dead_code)]
262        $($vis)* fn $random_fn<T, $($it: Iterator<Item = T>),*>(
263            seed: Seed,
264            $($xs_gen: &dyn Fn(Seed) -> $it,)*
265            output_to_input_map: &[usize],
266        ) -> $random_struct<T, $($it),*> {
267            $(
268                let _max_input_index = $i;
269            )*
270            validate_oi_map(_max_input_index, output_to_input_map.iter().cloned());
271            $random_struct {
272                $($xs: $xs_gen(seed.fork(stringify!($xs))),)*
273                output_to_input_map: output_to_input_map.to_vec(),
274            }
275        }
276
277        /// This documentation applies not only to `random_vecs_length_2`, but also to
278        /// `random_vecs_length_3`, `random_vecs_length_4`, and so on. See
279        /// [`random_vecs_fixed_length`] for more information.
280        ///
281        /// Generates random length-$n$ [`Vec`]s with elements from $n$ iterators.
282        ///
283        /// The probability of a particular length-$n$ [`Vec`] being generated is the product of the
284        /// probabilities of each of its elements.
285        ///
286        /// `xs`, `ys`, `zs`, ... must be infinite.
287        ///
288        /// # Examples
289        /// See [here](self#random_vecs_length_2).
290        #[allow(dead_code)]
291        #[inline]
292        $($vis)* fn $random_1_to_1_fn<T, $($it: Iterator<Item = T>),*>(
293            seed: Seed,
294            $($xs_gen: &dyn Fn(Seed) -> $it,)*
295        ) -> $random_struct<T, $($it),*> {
296            $random_fn(seed, $($xs_gen,)* &[$($i),*])
297        }
298    }
299}
300
301random_vecs_fixed_length!(
302    (pub),
303    RandomFixedLengthVecs2Inputs,
304    random_vecs_fixed_length_2_inputs,
305    random_vecs_length_2,
306    [0, I, xs, xs_gen],
307    [1, J, ys, ys_gen]
308);
309
310/// Generates random [`Vec`]s using elements from an iterator and with lengths from another
311/// iterator.
312#[derive(Clone, Debug)]
313pub struct RandomVecs<T, I: Iterator<Item = u64>, J: Iterator<Item = T>> {
314    lengths: I,
315    xs: J,
316}
317
318impl<T, I: Iterator<Item = u64>, J: Iterator<Item = T>> Iterator for RandomVecs<T, I, J> {
319    type Item = Vec<T>;
320
321    fn next(&mut self) -> Option<Vec<T>> {
322        Some(
323            (&mut self.xs)
324                .take(usize::exact_from(self.lengths.next().unwrap()))
325                .collect(),
326        )
327    }
328}
329
330/// Generates random [`Vec`]s using elements from an iterator and with lengths from another
331/// iterator.
332///
333/// The probability of a particular [`Vec`] being generated is the product of the probabilities of
334/// each of its elements, multiplied by the probability of its length being generated.
335///
336/// `lengths` and `xs` must be infinite.
337///
338/// # Worst-case complexity per iteration
339/// $T(i) = O(T^{\prime\prime}(i) + \ell T^\prime(i))$
340///
341/// $M(i) = O(M^{\prime\prime}(i) + \ell M^\prime(i))$
342///
343/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
344/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`,
345/// $T^{\prime\prime}$ and $M^{\prime\prime}$ are the time and memory functions of `lengths`, and
346/// $\ell$ is the $i$th generated length.
347///
348/// # Examples
349/// ```
350/// use itertools::Itertools;
351/// use malachite_base::num::random::random_primitive_ints;
352/// use malachite_base::random::EXAMPLE_SEED;
353/// use malachite_base::vecs::random::random_vecs_from_length_iterator;
354/// use malachite_base::vecs::random_values_from_vec;
355///
356/// let xs = random_vecs_from_length_iterator(
357///     EXAMPLE_SEED,
358///     &|seed| random_values_from_vec(seed, vec![0, 2, 4]),
359///     &random_primitive_ints::<u8>,
360/// );
361/// let values = xs.take(20).collect_vec();
362/// assert_eq!(
363///     values.iter().map(Vec::as_slice).collect_vec().as_slice(),
364///     &[
365///         &[85, 11][..],
366///         &[136, 200, 235, 134],
367///         &[203, 223],
368///         &[38, 235, 217, 177],
369///         &[162, 32, 166, 234],
370///         &[30, 218],
371///         &[],
372///         &[90, 106],
373///         &[],
374///         &[9, 216, 204, 151],
375///         &[213, 97, 253, 78],
376///         &[91, 39],
377///         &[191, 175, 170, 232],
378///         &[233, 2],
379///         &[35, 22, 217, 198],
380///         &[114, 17, 32, 173],
381///         &[114, 65, 121, 222],
382///         &[],
383///         &[173, 25, 144, 148],
384///         &[]
385///     ]
386/// );
387/// ```
388#[inline]
389pub fn random_vecs_from_length_iterator<T, I: Iterator<Item = u64>, J: Iterator<Item = T>>(
390    seed: Seed,
391    lengths_gen: &dyn Fn(Seed) -> I,
392    xs_gen: &dyn Fn(Seed) -> J,
393) -> RandomVecs<T, I, J> {
394    RandomVecs {
395        lengths: lengths_gen(seed.fork("lengths")),
396        xs: xs_gen(seed.fork("xs")),
397    }
398}
399
400/// Generates random [`Vec`]s using elements from an iterator.
401///
402/// The lengths of the [`Vec`]s are sampled from a geometric distribution with a specified mean $m$,
403/// equal to `mean_length_numerator / mean_length_denominator`. $m$ must be greater than 0.
404///
405/// $$
406/// P((x\_i)\_{i=0}^{n-1}) = \frac{m^n}{(m+1)^{n+1}}\prod_{i=0}^{n-1}P(x_i).
407/// $$
408///
409/// `xs_gen` must be infinite.
410///
411/// # Expected complexity per iteration
412/// $T(i) = O(m T^\prime(i))$
413///
414/// $M(i) = O(m M^\prime(i))$
415///
416/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
417/// $M^\prime$ are the time and memory functions of `xs`, and $m$ is `mean_length_numerator /
418/// mean_length_denominator`.
419///
420/// # Panics
421/// Panics if `mean_length_numerator` or `mean_length_denominator` are zero, or, if after being
422/// reduced to lowest terms, their sum is greater than or equal to $2^{64}$.
423///
424/// # Examples
425/// ```
426/// use itertools::Itertools;
427/// use malachite_base::num::random::random_primitive_ints;
428/// use malachite_base::random::EXAMPLE_SEED;
429/// use malachite_base::vecs::random::random_vecs;
430///
431/// let xs = random_vecs(EXAMPLE_SEED, &random_primitive_ints::<u8>, 4, 1);
432/// let values = xs.take(20).collect_vec();
433/// assert_eq!(
434///     values.iter().map(Vec::as_slice).collect_vec().as_slice(),
435///     &[
436///         &[][..],
437///         &[85, 11, 136, 200, 235, 134, 203, 223, 38, 235, 217, 177, 162, 32],
438///         &[166, 234, 30, 218],
439///         &[90, 106, 9, 216],
440///         &[204],
441///         &[],
442///         &[151, 213, 97, 253, 78],
443///         &[91, 39],
444///         &[191, 175, 170, 232],
445///         &[],
446///         &[233, 2, 35, 22, 217, 198],
447///         &[],
448///         &[],
449///         &[114, 17, 32, 173, 114, 65, 121, 222, 173, 25, 144],
450///         &[148, 79, 115, 52, 73, 69, 137, 91],
451///         &[],
452///         &[153, 178, 112],
453///         &[],
454///         &[34, 95, 106, 167, 197],
455///         &[130, 168, 122, 207, 172, 177, 86, 150, 221]
456///     ]
457/// );
458/// ```
459#[inline]
460pub fn random_vecs<I: Iterator>(
461    seed: Seed,
462    xs_gen: &dyn Fn(Seed) -> I,
463    mean_length_numerator: u64,
464    mean_length_denominator: u64,
465) -> RandomVecs<I::Item, GeometricRandomNaturalValues<u64>, I> {
466    random_vecs_from_length_iterator(
467        seed,
468        &|seed_2| {
469            geometric_random_unsigneds(seed_2, mean_length_numerator, mean_length_denominator)
470        },
471        xs_gen,
472    )
473}
474
475/// Generates random [`Vec`]s with a minimum length, using elements from an iterator.
476///
477/// The lengths of the [`Vec`]s are sampled from a geometric distribution with a specified mean $m$,
478/// equal to `mean_length_numerator / mean_length_denominator`. $m$ must be greater than
479/// `min_length`.
480///
481/// $$
482/// P((x\_i)\_{i=0}^{n-1}) = \\begin{cases}
483///     \frac{(m-a)^{n-a}}{(m+1-a)^{n+1-a}}\prod_{i=0}^{n-1}P(x_i) & \text{if} \\quad n\geq a, \\\\
484///     0 & \\text{otherwise},
485/// \\end{cases}
486/// $$
487/// where $a$ is `min_length`.
488///
489/// `xs_gen` must be infinite.
490///
491/// # Expected complexity per iteration
492/// $T(i) = O(m T^\prime(i))$
493///
494/// $M(i) = O(m M^\prime(i))$
495///
496/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
497/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`, and $m$ is
498/// `mean_length_numerator / mean_length_denominator`.
499///
500/// # Panics
501/// Panics if `mean_length_numerator` or `mean_length_denominator` are zero, if their ratio is less
502/// than or equal to `min_length`, or if they are too large and manipulating them leads to
503/// arithmetic overflow.
504///
505/// # Examples
506/// ```
507/// use itertools::Itertools;
508/// use malachite_base::num::random::random_primitive_ints;
509/// use malachite_base::random::EXAMPLE_SEED;
510/// use malachite_base::vecs::random::random_vecs_min_length;
511///
512/// let xs = random_vecs_min_length(EXAMPLE_SEED, 2, &random_primitive_ints::<u8>, 6, 1);
513/// let values = xs.take(20).collect_vec();
514/// assert_eq!(
515///     values.iter().map(Vec::as_slice).collect_vec().as_slice(),
516///     &[
517///         &[85, 11][..],
518///         &[136, 200, 235, 134, 203, 223, 38, 235, 217, 177, 162, 32, 166, 234, 30, 218],
519///         &[90, 106, 9, 216, 204, 151],
520///         &[213, 97, 253, 78, 91, 39],
521///         &[191, 175, 170],
522///         &[232, 233],
523///         &[2, 35, 22, 217, 198, 114, 17],
524///         &[32, 173, 114, 65],
525///         &[121, 222, 173, 25, 144, 148],
526///         &[79, 115],
527///         &[52, 73, 69, 137, 91, 153, 178, 112],
528///         &[34, 95],
529///         &[106, 167],
530///         &[197, 130, 168, 122, 207, 172, 177, 86, 150, 221, 218, 101, 115],
531///         &[74, 9, 123, 109, 52, 201, 159, 247, 250, 48],
532///         &[133, 235],
533///         &[196, 40, 97, 104, 68],
534///         &[190, 216],
535///         &[7, 216, 157, 43, 43, 112, 217],
536///         &[24, 11, 103, 211, 84, 135, 55, 29, 206, 89, 65]
537///     ]
538/// );
539/// ```
540#[inline]
541pub fn random_vecs_min_length<I: Iterator>(
542    seed: Seed,
543    min_length: u64,
544    xs_gen: &dyn Fn(Seed) -> I,
545    mean_length_numerator: u64,
546    mean_length_denominator: u64,
547) -> RandomVecs<I::Item, GeometricRandomNaturalValues<u64>, I> {
548    random_vecs_from_length_iterator(
549        seed,
550        &|seed_2| {
551            geometric_random_unsigned_inclusive_range(
552                seed_2,
553                min_length,
554                u64::MAX,
555                mean_length_numerator,
556                mean_length_denominator,
557            )
558        },
559        xs_gen,
560    )
561}
562
563/// Generates random [`Vec`]s with lengths in $[a, b)$, using elements from an iterator.
564///
565/// The lengths of the [`Vec`]s are sampled from a uniform distribution on $[a, b)$. $a$ must be
566/// less than $b$.
567///
568/// $$
569/// P((x\_i)\_{i=0}^{n-1}) = \\begin{cases}
570///     \frac{1}{b-a}\prod_{i=0}^{n-1}P(x_i) & \text{if} \\quad a \leq n < b, \\\\
571///     0 & \\text{otherwise}.
572/// \\end{cases}
573/// $$
574///
575/// `xs_gen` must be infinite.
576///
577/// # Expected complexity per iteration
578/// $T(i) = O(b T^\prime(i))$
579///
580/// $M(i) = O(b M^\prime(i))$
581///
582/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
583/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`, and $b$ is
584/// `b`.
585///
586/// # Panics
587/// Panics if $a \geq b$.
588///
589/// # Examples
590/// ```
591/// use itertools::Itertools;
592/// use malachite_base::num::random::random_primitive_ints;
593/// use malachite_base::random::EXAMPLE_SEED;
594/// use malachite_base::vecs::random::random_vecs_length_range;
595///
596/// let xs = random_vecs_length_range(EXAMPLE_SEED, 2, 5, &random_primitive_ints::<u8>);
597/// let values = xs.take(20).collect_vec();
598/// assert_eq!(
599///     values.iter().map(Vec::as_slice).collect_vec().as_slice(),
600///     &[
601///         &[85, 11, 136][..],
602///         &[200, 235, 134, 203],
603///         &[223, 38, 235],
604///         &[217, 177, 162, 32],
605///         &[166, 234, 30, 218],
606///         &[90, 106, 9],
607///         &[216, 204],
608///         &[151, 213, 97],
609///         &[253, 78],
610///         &[91, 39, 191, 175],
611///         &[170, 232, 233, 2],
612///         &[35, 22, 217],
613///         &[198, 114, 17, 32],
614///         &[173, 114, 65],
615///         &[121, 222, 173, 25],
616///         &[144, 148, 79, 115],
617///         &[52, 73, 69, 137],
618///         &[91, 153],
619///         &[178, 112, 34, 95],
620///         &[106, 167]
621///     ]
622/// );
623/// ```
624#[inline]
625pub fn random_vecs_length_range<I: Iterator>(
626    seed: Seed,
627    a: u64,
628    b: u64,
629    xs_gen: &dyn Fn(Seed) -> I,
630) -> RandomVecs<I::Item, RandomUnsignedRange<u64>, I> {
631    random_vecs_from_length_iterator(seed, &|seed_2| random_unsigned_range(seed_2, a, b), xs_gen)
632}
633
634/// Generates random [`Vec`]s with lengths in $[a, b]$, using elements from an iterator.
635///
636/// The lengths of the [`Vec`]s are sampled from a uniform distribution on $[a, b]$. $a$ must be
637/// less than or equal to $b$.
638///
639/// $$
640/// P((x\_i)\_{i=0}^{n-1}) = \\begin{cases}
641///     \frac{1}{b-a+1}\prod_{i=0}^{n-1}P(x_i) & \text{if} \\quad a \leq n \leq b, \\\\
642///     0 & \\text{otherwise}.
643/// \\end{cases}
644/// $$
645///
646/// `xs_gen` must be infinite.
647///
648/// # Expected complexity per iteration
649/// $T(i) = O(b T^\prime(i))$
650///
651/// $M(i) = O(b M^\prime(i))$
652///
653/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
654/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`, and $b$ is
655/// `b`.
656///
657/// # Panics
658/// Panics if $a > b$.
659///
660/// # Examples
661/// ```
662/// use itertools::Itertools;
663/// use malachite_base::num::random::random_primitive_ints;
664/// use malachite_base::random::EXAMPLE_SEED;
665/// use malachite_base::vecs::random::random_vecs_length_inclusive_range;
666///
667/// let xs = random_vecs_length_inclusive_range(EXAMPLE_SEED, 2, 4, &random_primitive_ints::<u8>);
668/// let values = xs.take(20).collect_vec();
669/// assert_eq!(
670///     values.iter().map(Vec::as_slice).collect_vec().as_slice(),
671///     &[
672///         &[85, 11, 136][..],
673///         &[200, 235, 134, 203],
674///         &[223, 38, 235],
675///         &[217, 177, 162, 32],
676///         &[166, 234, 30, 218],
677///         &[90, 106, 9],
678///         &[216, 204],
679///         &[151, 213, 97],
680///         &[253, 78],
681///         &[91, 39, 191, 175],
682///         &[170, 232, 233, 2],
683///         &[35, 22, 217],
684///         &[198, 114, 17, 32],
685///         &[173, 114, 65],
686///         &[121, 222, 173, 25],
687///         &[144, 148, 79, 115],
688///         &[52, 73, 69, 137],
689///         &[91, 153],
690///         &[178, 112, 34, 95],
691///         &[106, 167]
692///     ]
693/// );
694/// ```
695#[inline]
696pub fn random_vecs_length_inclusive_range<I: Iterator>(
697    seed: Seed,
698    a: u64,
699    b: u64,
700    xs_gen: &dyn Fn(Seed) -> I,
701) -> RandomVecs<I::Item, RandomUnsignedInclusiveRange<u64>, I> {
702    random_vecs_from_length_iterator(
703        seed,
704        &|seed_2| random_unsigned_inclusive_range(seed_2, a, b),
705        xs_gen,
706    )
707}
708
709#[doc(hidden)]
710#[derive(Clone, Debug)]
711pub struct RandomOrderedUniqueVecsLength2<I: Iterator>
712where
713    I::Item: Ord,
714{
715    xs: I,
716}
717
718impl<I: Iterator> Iterator for RandomOrderedUniqueVecsLength2<I>
719where
720    I::Item: Ord,
721{
722    type Item = Vec<I::Item>;
723
724    #[inline]
725    fn next(&mut self) -> Option<Vec<I::Item>> {
726        let mut out = Vec::with_capacity(2);
727        loop {
728            let x = self.xs.next().unwrap();
729            if out.is_empty() {
730                out.push(x);
731            } else {
732                match x.cmp(&out[0]) {
733                    Equal => {}
734                    Greater => {
735                        out.push(x);
736                        break;
737                    }
738                    Less => {
739                        out.insert(0, x);
740                        break;
741                    }
742                }
743            }
744        }
745        Some(out)
746    }
747}
748
749#[doc(hidden)]
750#[derive(Clone, Debug)]
751pub struct RandomOrderedUniqueVecsFixedLengthGreaterThan2<I: Iterator>
752where
753    I::Item: Ord,
754{
755    xs: RandomBTreeSetsFixedLength<I>,
756}
757
758impl<I: Iterator> Iterator for RandomOrderedUniqueVecsFixedLengthGreaterThan2<I>
759where
760    I::Item: Ord,
761{
762    type Item = Vec<I::Item>;
763
764    #[inline]
765    fn next(&mut self) -> Option<Vec<I::Item>> {
766        Some(self.xs.next().unwrap().into_iter().collect())
767    }
768}
769
770/// Generates random [`Vec`]s of a fixed length, where the [`Vec`]s have no repeated elements, and
771/// the elements are in ascending order.
772///
773/// This `struct` is created by [`random_ordered_unique_vecs_fixed_length`]; see its documentation
774/// for more.
775#[derive(Clone, Debug)]
776pub enum RandomOrderedUniqueVecsFixedLength<I: Iterator>
777where
778    I::Item: Ord,
779{
780    Zero,
781    One(I),
782    Two(RandomOrderedUniqueVecsLength2<I>),
783    GreaterThan2(RandomOrderedUniqueVecsFixedLengthGreaterThan2<I>),
784}
785
786impl<I: Iterator> Iterator for RandomOrderedUniqueVecsFixedLength<I>
787where
788    I::Item: Ord,
789{
790    type Item = Vec<I::Item>;
791
792    #[inline]
793    fn next(&mut self) -> Option<Vec<I::Item>> {
794        match self {
795            Self::Zero => Some(vec![]),
796            Self::One(xs) => xs.next().map(|x| vec![x]),
797            Self::Two(xs) => xs.next(),
798            Self::GreaterThan2(xs) => xs.next(),
799        }
800    }
801}
802
803/// Randomly generates [`Vec`]s of a given length, where the [`Vec`]s have no repeated elements, and
804/// the elements are in ascending order.
805///
806/// The input iterator must generate at least `len` distinct elements; otherwise, this iterator will
807/// hang.
808///
809/// $$
810/// P((x\_i)\_{i=0}^{n-1}) = n!\prod\_{i=0}^{n-1}P(x\_i).
811/// $$
812///
813/// The above formula assumes that the [`Vec`] is valid, \emph{i.e.} its elements are strictly
814/// increasing. The probability of an invalid [`Vec`] is zero.
815///
816/// If `len` is 0, the output consists of the empty list, repeated.
817///
818/// `xs` must be infinite.
819///
820/// # Expected complexity per iteration
821/// $T(i) = O(\ell^2 + \ell T^\prime(i))$
822///
823/// $M(i) = O(\ell M^\prime(i))$
824///
825/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
826/// $M^\prime$ are the time and memory functions of `xs`, and $\ell$ is `len`; sorted insertion is
827/// quadratic in the length.
828///
829/// If `xs` can repeat values, extra draws are needed to reach the required number of distinct
830/// elements, and an iteration fails to terminate if fewer distinct values are reachable than the
831/// requested length.
832///
833/// # Expected complexity per iteration
834/// $T(i) = O(m^2 + m T^\prime(i))$
835///
836/// $M(i) = O(m M^\prime(i))$
837///
838/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
839/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`, and $m$ is
840/// `mean_length_numerator / mean_length_denominator`.
841///
842/// If `xs` can repeat values, extra draws are needed to reach the required number of distinct
843/// elements, and an iteration fails to terminate if fewer distinct values are reachable than the
844/// requested length.
845///
846/// # Examples
847/// ```
848/// use itertools::Itertools;
849/// use malachite_base::num::random::random_unsigned_inclusive_range;
850/// use malachite_base::random::EXAMPLE_SEED;
851/// use malachite_base::vecs::random::random_ordered_unique_vecs_fixed_length;
852///
853/// let xss = random_ordered_unique_vecs_fixed_length(
854///     2,
855///     random_unsigned_inclusive_range::<u32>(EXAMPLE_SEED, 1, 100),
856/// )
857/// .take(10)
858/// .collect_vec();
859/// assert_eq!(
860///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
861///     &[
862///         &[24, 95],
863///         &[71, 99],
864///         &[53, 93],
865///         &[34, 85],
866///         &[2, 48],
867///         &[11, 55],
868///         &[18, 48],
869///         &[90, 93],
870///         &[67, 93],
871///         &[93, 95]
872///     ]
873/// );
874/// ```
875#[inline]
876pub fn random_ordered_unique_vecs_fixed_length<I: Iterator>(
877    len: u64,
878    xs: I,
879) -> RandomOrderedUniqueVecsFixedLength<I>
880where
881    I::Item: Ord,
882{
883    match len {
884        0 => RandomOrderedUniqueVecsFixedLength::Zero,
885        1 => RandomOrderedUniqueVecsFixedLength::One(xs),
886        2 => RandomOrderedUniqueVecsFixedLength::Two(RandomOrderedUniqueVecsLength2 { xs }),
887        len => RandomOrderedUniqueVecsFixedLength::GreaterThan2(
888            RandomOrderedUniqueVecsFixedLengthGreaterThan2 {
889                xs: random_b_tree_sets_fixed_length(len, xs),
890            },
891        ),
892    }
893}
894
895/// Generates random [`Vec`]s with lengths from an iterator, where the [`Vec`]s have no repeated
896/// elements, and the elements are in ascending order.
897#[derive(Clone, Debug)]
898pub struct RandomOrderedUniqueVecs<T: Ord, I: Iterator<Item = u64>, J: Iterator<Item = T>> {
899    xs: RandomBTreeSets<T, I, J>,
900}
901
902impl<T: Ord, I: Iterator<Item = u64>, J: Iterator<Item = T>> Iterator
903    for RandomOrderedUniqueVecs<T, I, J>
904{
905    type Item = Vec<T>;
906
907    #[inline]
908    fn next(&mut self) -> Option<Vec<T>> {
909        Some(self.xs.next().unwrap().into_iter().collect())
910    }
911}
912
913/// Generates random [`Vec`]s using elements from an iterator and with lengths from another
914/// iterator, where the [`Vec`]s have no repeated elements, and the elements are in ascending order.
915///
916/// The input iterator must generate at least many distinct elements as any number generated by the
917/// lengths iterator; otherwise, this iterator will hang.
918///
919/// $$
920/// P((x\_i)\_{i=0}^{n-1}) = n!P(n)\prod\_{i=0}^{n-1}P(x\_i).
921/// $$
922///
923/// The above formula assumes that the [`Vec`] is valid, \emph{i.e.} its elements are strictly
924/// increasing. The probability of an invalid [`Vec`] is zero.
925///
926/// `lengths` and `xs` must be infinite.
927///
928/// # Expected complexity per iteration
929/// $T(i) = O(T^{\prime\prime}(i) + \ell^2 + \ell T^\prime(i))$
930///
931/// $M(i) = O(M^{\prime\prime}(i) + \ell M^\prime(i))$
932///
933/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
934/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`,
935/// $T^{\prime\prime}$ and $M^{\prime\prime}$ are the time and memory functions of `lengths`, and
936/// $\ell$ is the $i$th generated length.
937///
938/// If `xs` can repeat values, extra draws are needed to reach the required number of distinct
939/// elements, and an iteration fails to terminate if fewer distinct values are reachable than the
940/// requested length.
941///
942/// # Examples
943/// ```
944/// use itertools::Itertools;
945/// use malachite_base::num::random::random_primitive_ints;
946/// use malachite_base::random::EXAMPLE_SEED;
947/// use malachite_base::vecs::random::random_ordered_unique_vecs_from_length_iterator;
948/// use malachite_base::vecs::random_values_from_vec;
949///
950/// let xs = random_ordered_unique_vecs_from_length_iterator(
951///     EXAMPLE_SEED,
952///     &|seed| random_values_from_vec(seed, vec![0, 2, 4]),
953///     &random_primitive_ints::<u8>,
954/// );
955/// let values = xs.take(20).collect_vec();
956/// assert_eq!(
957///     values.iter().map(Vec::as_slice).collect_vec().as_slice(),
958///     &[
959///         &[11, 85][..],
960///         &[134, 136, 200, 235],
961///         &[203, 223],
962///         &[38, 177, 217, 235],
963///         &[32, 162, 166, 234],
964///         &[30, 218],
965///         &[],
966///         &[90, 106],
967///         &[],
968///         &[9, 151, 204, 216],
969///         &[78, 97, 213, 253],
970///         &[39, 91],
971///         &[170, 175, 191, 232],
972///         &[2, 233],
973///         &[22, 35, 198, 217],
974///         &[17, 32, 114, 173],
975///         &[65, 114, 121, 222],
976///         &[],
977///         &[25, 144, 148, 173],
978///         &[]
979///     ]
980/// );
981/// ```
982#[inline]
983pub fn random_ordered_unique_vecs_from_length_iterator<
984    T: Ord,
985    I: Iterator<Item = u64>,
986    J: Iterator<Item = T>,
987>(
988    seed: Seed,
989    lengths_gen: &dyn Fn(Seed) -> I,
990    xs_gen: &dyn Fn(Seed) -> J,
991) -> RandomOrderedUniqueVecs<T, I, J> {
992    RandomOrderedUniqueVecs {
993        xs: random_b_tree_sets_from_length_iterator(seed, lengths_gen, xs_gen),
994    }
995}
996
997/// Generates random [`Vec`]s using elements from an iterator, where the [`Vec`]s have no repeated
998/// elements, and the elements are in ascending order.
999///
1000/// The lengths of the [`Vec`]s are sampled from a geometric distribution with a specified mean $m$,
1001/// equal to `mean_length_numerator / mean_length_denominator`. $m$ must be greater than 0.
1002///
1003/// Strictly speaking, the input iterator must generate infinitely many distinct elements. In
1004/// practice it only needs to generate $k$ distinct elements, where $k$ is the largest length
1005/// actually sampled from the geometric distribution. For example, if `mean_length_numerator /
1006/// mean_length_denominator` is significantly lower than 256, then it's ok to use
1007/// `random_unsigneds::<u8>`.
1008///
1009/// $$
1010/// P((x\_i)\_{i=0}^{n-1}) = n!P_g(n)\prod\_{i=0}^{n-1}P(x\_i),
1011/// $$
1012/// where $P_g(n)$ is the probability function described in [`geometric_random_unsigneds`].
1013///
1014/// `xs_gen` must be infinite.
1015///
1016/// # Expected complexity per iteration
1017/// $T(i) = O(m T^\prime(i))$
1018///
1019/// $M(i) = O(m M^\prime(i))$
1020///
1021/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
1022/// $M^\prime$ are the time and memory functions of `xs`, and $m$ is `mean_length_numerator /
1023/// mean_length_denominator`.
1024///
1025/// # Panics
1026/// Panics if `mean_length_numerator` or `mean_length_denominator` are zero, or, if after being
1027/// reduced to lowest terms, their sum is greater than or equal to $2^{64}$.
1028///
1029/// # Examples
1030/// ```
1031/// use itertools::Itertools;
1032/// use malachite_base::num::random::random_primitive_ints;
1033/// use malachite_base::random::EXAMPLE_SEED;
1034/// use malachite_base::vecs::random::random_ordered_unique_vecs;
1035///
1036/// let xs = random_ordered_unique_vecs(EXAMPLE_SEED, &random_primitive_ints::<u8>, 4, 1);
1037/// let values = xs.take(20).collect_vec();
1038/// assert_eq!(
1039///     values.iter().map(Vec::as_slice).collect_vec().as_slice(),
1040///     &[
1041///         &[][..],
1042///         &[11, 32, 38, 85, 134, 136, 162, 166, 177, 200, 203, 217, 223, 235],
1043///         &[30, 90, 218, 234],
1044///         &[9, 106, 204, 216],
1045///         &[151],
1046///         &[],
1047///         &[78, 91, 97, 213, 253],
1048///         &[39, 191],
1049///         &[170, 175, 232, 233],
1050///         &[],
1051///         &[2, 22, 35, 114, 198, 217],
1052///         &[],
1053///         &[],
1054///         &[17, 25, 32, 65, 79, 114, 121, 144, 148, 173, 222],
1055///         &[52, 69, 73, 91, 115, 137, 153, 178],
1056///         &[],
1057///         &[34, 95, 112],
1058///         &[],
1059///         &[106, 130, 167, 168, 197],
1060///         &[86, 101, 122, 150, 172, 177, 207, 218, 221]
1061///     ]
1062/// );
1063/// ```
1064#[inline]
1065pub fn random_ordered_unique_vecs<I: Iterator>(
1066    seed: Seed,
1067    xs_gen: &dyn Fn(Seed) -> I,
1068    mean_length_numerator: u64,
1069    mean_length_denominator: u64,
1070) -> RandomOrderedUniqueVecs<I::Item, GeometricRandomNaturalValues<u64>, I>
1071where
1072    I::Item: Ord,
1073{
1074    random_ordered_unique_vecs_from_length_iterator(
1075        seed,
1076        &|seed_2| {
1077            geometric_random_unsigneds(seed_2, mean_length_numerator, mean_length_denominator)
1078        },
1079        xs_gen,
1080    )
1081}
1082
1083/// Generates random [`Vec`]s with a minimum length, using elements from an iterator, where the
1084/// [`Vec`]s have no repeated elements, and the elements are in ascending order.
1085///
1086/// Strictly speaking, the input iterator must generate infinitely many distinct elements. In
1087/// practice it only needs to generate $k$ distinct elements, where $k$ is the largest length
1088/// actually sampled from the geometric distribution. For example, if `mean_length_numerator /
1089/// mean_length_denominator` is significantly lower than 256, then it's ok to use
1090/// `random_unsigneds::<u8>`.
1091///
1092/// $$
1093/// P((x\_i)\_{i=0}^{n-1}) = n!P_g(n)\prod\_{i=0}^{n-1}P(x\_i),
1094/// $$
1095/// where $P_g(n)$ is the probability function described in
1096/// [`geometric_random_unsigned_inclusive_range`], with $a$ equal to `min_length` and `b` to
1097/// `u64::MAX`.
1098///
1099/// `xs_gen` must be infinite.
1100///
1101/// # Expected complexity per iteration
1102/// $T(i) = O(m^2 + m T^\prime(i))$
1103///
1104/// $M(i) = O(m M^\prime(i))$
1105///
1106/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
1107/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`, and $m$ is
1108/// `mean_length_numerator / mean_length_denominator`.
1109///
1110/// If `xs` can repeat values, extra draws are needed to reach the required number of distinct
1111/// elements, and an iteration fails to terminate if fewer distinct values are reachable than the
1112/// requested length.
1113///
1114/// # Panics
1115/// Panics if `mean_length_numerator` or `mean_length_denominator` are zero, if their ratio is less
1116/// than or equal to `min_length`, or if they are too large and manipulating them leads to
1117/// arithmetic overflow.
1118///
1119/// # Examples
1120/// ```
1121/// use itertools::Itertools;
1122/// use malachite_base::num::random::random_primitive_ints;
1123/// use malachite_base::random::EXAMPLE_SEED;
1124/// use malachite_base::vecs::random::random_ordered_unique_vecs_min_length;
1125///
1126/// let xs =
1127///     random_ordered_unique_vecs_min_length(EXAMPLE_SEED, 2, &random_primitive_ints::<u8>, 6, 1);
1128/// let values = xs.take(20).collect_vec();
1129/// assert_eq!(
1130///     values.iter().map(Vec::as_slice).collect_vec().as_slice(),
1131///     &[
1132///         &[11, 85][..],
1133///         &[30, 32, 38, 90, 134, 136, 162, 166, 177, 200, 203, 217, 218, 223, 234, 235],
1134///         &[9, 106, 151, 204, 213, 216],
1135///         &[39, 78, 91, 97, 191, 253],
1136///         &[170, 175, 232],
1137///         &[2, 233],
1138///         &[17, 22, 32, 35, 114, 198, 217],
1139///         &[65, 114, 121, 173],
1140///         &[25, 79, 144, 148, 173, 222],
1141///         &[52, 115],
1142///         &[34, 69, 73, 91, 112, 137, 153, 178],
1143///         &[95, 106],
1144///         &[167, 197],
1145///         &[74, 86, 101, 115, 122, 130, 150, 168, 172, 177, 207, 218, 221],
1146///         &[9, 48, 52, 109, 123, 133, 159, 201, 247, 250],
1147///         &[196, 235],
1148///         &[40, 68, 97, 104, 190],
1149///         &[7, 216],
1150///         &[11, 24, 43, 112, 157, 216, 217],
1151///         &[29, 51, 55, 65, 84, 89, 103, 135, 191, 206, 211]
1152///     ]
1153/// );
1154/// ```
1155#[inline]
1156pub fn random_ordered_unique_vecs_min_length<I: Iterator>(
1157    seed: Seed,
1158    min_length: u64,
1159    xs_gen: &dyn Fn(Seed) -> I,
1160    mean_length_numerator: u64,
1161    mean_length_denominator: u64,
1162) -> RandomOrderedUniqueVecs<I::Item, GeometricRandomNaturalValues<u64>, I>
1163where
1164    I::Item: Ord,
1165{
1166    random_ordered_unique_vecs_from_length_iterator(
1167        seed,
1168        &|seed_2| {
1169            geometric_random_unsigned_inclusive_range(
1170                seed_2,
1171                min_length,
1172                u64::MAX,
1173                mean_length_numerator,
1174                mean_length_denominator,
1175            )
1176        },
1177        xs_gen,
1178    )
1179}
1180
1181/// Generates random [`Vec`]s with lengths in $[a, b)$, using elements from an iterator, where the
1182/// [`Vec`]s have no repeated elements, and the elements are in ascending order.
1183///
1184/// The lengths of the [`Vec`]s are sampled from a uniform distribution on $[a, b)$. $a$ must be
1185/// less than $b$.
1186///
1187/// The input iterator must generate at least $b$ distinct elements.
1188///
1189/// $$
1190/// P((x\_i)\_{i=0}^{n-1}, a, b) = \frac{n!}{b - a}\prod\_{i=0}^{n-1}P(x\_i).
1191/// $$
1192///
1193/// `xs_gen` must be infinite.
1194///
1195/// # Expected complexity per iteration
1196/// $T(i) = O(b^2 + b T^\prime(i))$
1197///
1198/// $M(i) = O(b M^\prime(i))$
1199///
1200/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
1201/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`, and $b$ is
1202/// `b`.
1203///
1204/// If `xs` can repeat values, extra draws are needed to reach the required number of distinct
1205/// elements, and an iteration fails to terminate if fewer distinct values are reachable than the
1206/// requested length.
1207///
1208/// # Panics
1209/// Panics if $a \geq b$.
1210///
1211/// # Examples
1212/// ```
1213/// use itertools::Itertools;
1214/// use malachite_base::num::random::random_primitive_ints;
1215/// use malachite_base::random::EXAMPLE_SEED;
1216/// use malachite_base::vecs::random::random_ordered_unique_vecs_length_range;
1217///
1218/// let xs =
1219///     random_ordered_unique_vecs_length_range(EXAMPLE_SEED, 2, 5, &random_primitive_ints::<u8>);
1220/// let values = xs.take(20).collect_vec();
1221/// assert_eq!(
1222///     values.iter().map(Vec::as_slice).collect_vec().as_slice(),
1223///     &[
1224///         &[11, 85, 136][..],
1225///         &[134, 200, 203, 235],
1226///         &[38, 223, 235],
1227///         &[32, 162, 177, 217],
1228///         &[30, 166, 218, 234],
1229///         &[9, 90, 106],
1230///         &[204, 216],
1231///         &[97, 151, 213],
1232///         &[78, 253],
1233///         &[39, 91, 175, 191],
1234///         &[2, 170, 232, 233],
1235///         &[22, 35, 217],
1236///         &[17, 32, 114, 198],
1237///         &[65, 114, 173],
1238///         &[25, 121, 173, 222],
1239///         &[79, 115, 144, 148],
1240///         &[52, 69, 73, 137],
1241///         &[91, 153],
1242///         &[34, 95, 112, 178],
1243///         &[106, 167]
1244///     ]
1245/// );
1246/// ```
1247#[inline]
1248pub fn random_ordered_unique_vecs_length_range<I: Iterator>(
1249    seed: Seed,
1250    a: u64,
1251    b: u64,
1252    xs_gen: &dyn Fn(Seed) -> I,
1253) -> RandomOrderedUniqueVecs<I::Item, RandomUnsignedRange<u64>, I>
1254where
1255    I::Item: Ord,
1256{
1257    random_ordered_unique_vecs_from_length_iterator(
1258        seed,
1259        &|seed_2| random_unsigned_range(seed_2, a, b),
1260        xs_gen,
1261    )
1262}
1263
1264/// Generates random [`Vec`]s with lengths in $[a, b]$, using elements from an iterator, where the
1265/// [`Vec`]s have no repeated elements, and the elements are in ascending order.
1266///
1267/// The lengths of the [`Vec`]s are sampled from a uniform distribution on $[a, b]$. $a$ must be
1268/// less than or equal to $b$.
1269///
1270/// The input iterator must generate at least $b$ distinct elements.
1271///
1272/// $$
1273/// P((x\_i)\_{i=0}^{n-1}, a, b) = \frac{n!}{b - a + 1}\prod\_{i=0}^{n-1}P(x\_i).
1274/// $$
1275///
1276/// `xs_gen` must be infinite.
1277///
1278/// # Expected complexity per iteration
1279/// $T(i) = O(b^2 + b T^\prime(i))$
1280///
1281/// $M(i) = O(b M^\prime(i))$
1282///
1283/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
1284/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`, and $b$ is
1285/// `b`.
1286///
1287/// If `xs` can repeat values, extra draws are needed to reach the required number of distinct
1288/// elements, and an iteration fails to terminate if fewer distinct values are reachable than the
1289/// requested length.
1290///
1291/// # Panics
1292/// Panics if $a > b$.
1293///
1294/// # Examples
1295/// ```
1296/// use itertools::Itertools;
1297/// use malachite_base::num::random::random_primitive_ints;
1298/// use malachite_base::random::EXAMPLE_SEED;
1299/// use malachite_base::vecs::random::random_ordered_unique_vecs_length_inclusive_range;
1300///
1301/// let xs = random_ordered_unique_vecs_length_inclusive_range(
1302///     EXAMPLE_SEED,
1303///     2,
1304///     4,
1305///     &random_primitive_ints::<u8>,
1306/// );
1307/// let values = xs.take(20).collect_vec();
1308/// assert_eq!(
1309///     values.iter().map(Vec::as_slice).collect_vec().as_slice(),
1310///     &[
1311///         &[11, 85, 136][..],
1312///         &[134, 200, 203, 235],
1313///         &[38, 223, 235],
1314///         &[32, 162, 177, 217],
1315///         &[30, 166, 218, 234],
1316///         &[9, 90, 106],
1317///         &[204, 216],
1318///         &[97, 151, 213],
1319///         &[78, 253],
1320///         &[39, 91, 175, 191],
1321///         &[2, 170, 232, 233],
1322///         &[22, 35, 217],
1323///         &[17, 32, 114, 198],
1324///         &[65, 114, 173],
1325///         &[25, 121, 173, 222],
1326///         &[79, 115, 144, 148],
1327///         &[52, 69, 73, 137],
1328///         &[91, 153],
1329///         &[34, 95, 112, 178],
1330///         &[106, 167]
1331///     ]
1332/// );
1333/// ```
1334#[inline]
1335pub fn random_ordered_unique_vecs_length_inclusive_range<I: Iterator>(
1336    seed: Seed,
1337    a: u64,
1338    b: u64,
1339    xs_gen: &dyn Fn(Seed) -> I,
1340) -> RandomOrderedUniqueVecs<I::Item, RandomUnsignedInclusiveRange<u64>, I>
1341where
1342    I::Item: Ord,
1343{
1344    random_ordered_unique_vecs_from_length_iterator(
1345        seed,
1346        &|seed_2| random_unsigned_inclusive_range(seed_2, a, b),
1347        xs_gen,
1348    )
1349}
1350
1351#[doc(hidden)]
1352#[derive(Clone, Debug)]
1353pub struct RandomUniqueVecsLength2<I: Iterator>
1354where
1355    I::Item: Eq,
1356{
1357    xs: I,
1358}
1359
1360impl<I: Iterator> Iterator for RandomUniqueVecsLength2<I>
1361where
1362    I::Item: Eq,
1363{
1364    type Item = Vec<I::Item>;
1365
1366    #[inline]
1367    fn next(&mut self) -> Option<Vec<I::Item>> {
1368        let mut out = Vec::with_capacity(2);
1369        loop {
1370            let x = self.xs.next().unwrap();
1371            if out.is_empty() {
1372                out.push(x);
1373            } else if x != out[0] {
1374                out.push(x);
1375                return Some(out);
1376            }
1377        }
1378    }
1379}
1380
1381/// Generates random [`Vec`]s with lengths from an iterator, where the [`Vec`]s have no repeated
1382/// elements.
1383#[derive(Clone, Debug)]
1384pub struct RandomUniqueVecs<T: Eq + Hash, I: Iterator<Item = u64>, J: Iterator<Item = T>> {
1385    lengths: I,
1386    xs: J,
1387}
1388
1389impl<T: Eq + Hash, I: Iterator<Item = u64>, J: Iterator<Item = T>> Iterator
1390    for RandomUniqueVecs<T, I, J>
1391{
1392    type Item = Vec<T>;
1393
1394    fn next(&mut self) -> Option<Vec<T>> {
1395        // We avoid cloning the T values. We first move them into a HashMap, then into a
1396        // Vec<Option<T>>, then into the output Vec<T>.
1397        let len = usize::exact_from(self.lengths.next().unwrap());
1398        let mut xs_to_indices = HashMap::with_capacity(len);
1399        let mut i = 0;
1400        while i < len {
1401            xs_to_indices
1402                .entry(self.xs.next().unwrap())
1403                .or_insert_with(|| {
1404                    i += 1;
1405                    i - 1
1406                });
1407        }
1408        let mut out = Vec::with_capacity(len);
1409        out.resize_with(len, || None);
1410        for (x, i) in xs_to_indices {
1411            out[i] = Some(x);
1412        }
1413        Some(out.into_iter().map(Option::unwrap).collect())
1414    }
1415}
1416
1417/// Generates random [`Vec`]s using elements from an iterator and with lengths from another
1418/// iterator, where the [`Vec`]s have no repeated elements.
1419///
1420/// The input iterator must generate at least many distinct elements as any number generated by the
1421/// lengths iterator; otherwise, this iterator will hang.
1422///
1423/// `lengths` and `xs` must be infinite.
1424///
1425/// # Expected complexity per iteration
1426/// $T(i) = O(T^{\prime\prime}(i) + \ell T^\prime(i))$
1427///
1428/// $M(i) = O(M^{\prime\prime}(i) + \ell M^\prime(i))$
1429///
1430/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
1431/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`,
1432/// $T^{\prime\prime}$ and $M^{\prime\prime}$ are the time and memory functions of `lengths`, and
1433/// $\ell$ is the $i$th generated length.
1434///
1435/// If `xs` can repeat values, extra draws are needed to reach the required number of distinct
1436/// elements, and an iteration fails to terminate if fewer distinct values are reachable than the
1437/// requested length.
1438///
1439/// # Examples
1440/// ```
1441/// use itertools::Itertools;
1442/// use malachite_base::num::random::random_primitive_ints;
1443/// use malachite_base::random::EXAMPLE_SEED;
1444/// use malachite_base::vecs::random::random_unique_vecs_from_length_iterator;
1445/// use malachite_base::vecs::random_values_from_vec;
1446///
1447/// let xs = random_unique_vecs_from_length_iterator(
1448///     EXAMPLE_SEED,
1449///     &|seed| random_values_from_vec(seed, vec![0, 2, 4]),
1450///     &random_primitive_ints::<u8>,
1451/// );
1452/// let values = xs.take(20).collect_vec();
1453/// assert_eq!(
1454///     values.iter().map(Vec::as_slice).collect_vec().as_slice(),
1455///     &[
1456///         &[85, 11][..],
1457///         &[136, 200, 235, 134],
1458///         &[203, 223],
1459///         &[38, 235, 217, 177],
1460///         &[162, 32, 166, 234],
1461///         &[30, 218],
1462///         &[],
1463///         &[90, 106],
1464///         &[],
1465///         &[9, 216, 204, 151],
1466///         &[213, 97, 253, 78],
1467///         &[91, 39],
1468///         &[191, 175, 170, 232],
1469///         &[233, 2],
1470///         &[35, 22, 217, 198],
1471///         &[114, 17, 32, 173],
1472///         &[114, 65, 121, 222],
1473///         &[],
1474///         &[173, 25, 144, 148],
1475///         &[]
1476///     ]
1477/// );
1478/// ```
1479#[inline]
1480pub fn random_unique_vecs_from_length_iterator<
1481    T: Eq + Hash,
1482    I: Iterator<Item = u64>,
1483    J: Iterator<Item = T>,
1484>(
1485    seed: Seed,
1486    lengths_gen: &dyn Fn(Seed) -> I,
1487    xs_gen: &dyn Fn(Seed) -> J,
1488) -> RandomUniqueVecs<T, I, J> {
1489    RandomUniqueVecs {
1490        lengths: lengths_gen(seed.fork("lengths")),
1491        xs: xs_gen(seed.fork("xs")),
1492    }
1493}
1494
1495/// Generates random [`Vec`]s of a fixed length, where the [`Vec`]s have no repeated elements.
1496///
1497/// This `enum` is created by [`random_unique_vecs_fixed_length`]; see its documentation for more.
1498#[derive(Clone, Debug)]
1499pub enum RandomUniqueVecsFixedLength<I: Iterator>
1500where
1501    I::Item: Eq + Hash,
1502{
1503    Zero,
1504    One(I),
1505    Two(RandomUniqueVecsLength2<I>),
1506    GreaterThan2(RandomUniqueVecs<I::Item, Repeat<u64>, I>),
1507}
1508
1509impl<I: Iterator> Iterator for RandomUniqueVecsFixedLength<I>
1510where
1511    I::Item: Eq + Hash,
1512{
1513    type Item = Vec<I::Item>;
1514
1515    #[inline]
1516    fn next(&mut self) -> Option<Vec<I::Item>> {
1517        match self {
1518            Self::Zero => Some(vec![]),
1519            Self::One(xs) => xs.next().map(|x| vec![x]),
1520            Self::Two(xs) => xs.next(),
1521            Self::GreaterThan2(xs) => xs.next(),
1522        }
1523    }
1524}
1525
1526/// Randomly generates [`Vec`]s of a given length, where the [`Vec`]s have no repeated elements.
1527///
1528/// The input iterator must generate at least `len` distinct elements; otherwise, this iterator will
1529/// hang.
1530///
1531/// If `len` is 0, the output consists of the empty list, repeated.
1532///
1533/// `xs` must be infinite.
1534///
1535/// # Expected complexity per iteration
1536/// $T(i) = O(\ell T^\prime(i))$
1537///
1538/// $M(i) = O(\ell M^\prime(i))$
1539///
1540/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
1541/// $M^\prime$ are the time and memory functions of `xs`, and $\ell$ is `len`.
1542///
1543/// If `xs` can repeat values, extra draws are needed to reach the required number of distinct
1544/// elements, and an iteration fails to terminate if fewer distinct values are reachable than the
1545/// requested length.
1546///
1547/// # Expected complexity per iteration
1548/// $T(i) = O(m T^\prime(i))$
1549///
1550/// $M(i) = O(m M^\prime(i))$
1551///
1552/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
1553/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`, and $m$ is
1554/// `mean_length_numerator / mean_length_denominator`.
1555///
1556/// If `xs` can repeat values, extra draws are needed to reach the required number of distinct
1557/// elements, and an iteration fails to terminate if fewer distinct values are reachable than the
1558/// requested length.
1559///
1560/// # Examples
1561/// ```
1562/// use itertools::Itertools;
1563/// use malachite_base::num::random::random_unsigned_inclusive_range;
1564/// use malachite_base::random::EXAMPLE_SEED;
1565/// use malachite_base::vecs::random::random_unique_vecs_fixed_length;
1566///
1567/// let xss = random_unique_vecs_fixed_length(
1568///     2,
1569///     random_unsigned_inclusive_range::<u32>(EXAMPLE_SEED, 1, 100),
1570/// )
1571/// .take(10)
1572/// .collect_vec();
1573/// assert_eq!(
1574///     xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
1575///     &[
1576///         &[95, 24],
1577///         &[99, 71],
1578///         &[93, 53],
1579///         &[85, 34],
1580///         &[48, 2],
1581///         &[55, 11],
1582///         &[48, 18],
1583///         &[90, 93],
1584///         &[67, 93],
1585///         &[93, 95]
1586///     ]
1587/// );
1588/// ```
1589#[inline]
1590pub fn random_unique_vecs_fixed_length<I: Iterator>(
1591    len: u64,
1592    xs: I,
1593) -> RandomUniqueVecsFixedLength<I>
1594where
1595    I::Item: Eq + Hash,
1596{
1597    match len {
1598        0 => RandomUniqueVecsFixedLength::Zero,
1599        1 => RandomUniqueVecsFixedLength::One(xs),
1600        2 => RandomUniqueVecsFixedLength::Two(RandomUniqueVecsLength2 { xs }),
1601        len => RandomUniqueVecsFixedLength::GreaterThan2(RandomUniqueVecs {
1602            lengths: repeat(len),
1603            xs,
1604        }),
1605    }
1606}
1607
1608/// Generates random [`Vec`]s using elements from an iterator, where the [`Vec`]s have no repeated
1609/// elements.
1610///
1611/// The lengths of the [`Vec`]s are sampled from a geometric distribution with a specified mean $m$,
1612/// equal to `mean_length_numerator / mean_length_denominator`. $m$ must be greater than 0.
1613///
1614/// Strictly speaking, the input iterator must generate infinitely many distinct elements. In
1615/// practice it only needs to generate $k$ distinct elements, where $k$ is the largest length
1616/// actually sampled from the geometric distribution. For example, if `mean_length_numerator /
1617/// mean_length_denominator` is significantly lower than 256, then it's ok to use
1618/// `random_unsigneds::<u8>`.
1619///
1620/// `xs_gen` must be infinite.
1621///
1622/// # Expected complexity per iteration
1623/// $T(i) = O(m T^\prime(i))$
1624///
1625/// $M(i) = O(m M^\prime(i))$
1626///
1627/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
1628/// $M^\prime$ are the time and memory functions of `xs`, and $m$ is `mean_length_numerator /
1629/// mean_length_denominator`.
1630///
1631/// # Panics
1632/// Panics if `mean_length_numerator` or `mean_length_denominator` are zero, or, if after being
1633/// reduced to lowest terms, their sum is greater than or equal to $2^{64}$.
1634///
1635/// # Examples
1636/// ```
1637/// use itertools::Itertools;
1638/// use malachite_base::num::random::random_primitive_ints;
1639/// use malachite_base::random::EXAMPLE_SEED;
1640/// use malachite_base::vecs::random::random_unique_vecs;
1641///
1642/// let xs = random_unique_vecs(EXAMPLE_SEED, &random_primitive_ints::<u8>, 4, 1);
1643/// let values = xs.take(20).collect_vec();
1644/// assert_eq!(
1645///     values.iter().map(Vec::as_slice).collect_vec().as_slice(),
1646///     &[
1647///         &[][..],
1648///         &[85, 11, 136, 200, 235, 134, 203, 223, 38, 217, 177, 162, 32, 166],
1649///         &[234, 30, 218, 90],
1650///         &[106, 9, 216, 204],
1651///         &[151],
1652///         &[],
1653///         &[213, 97, 253, 78, 91],
1654///         &[39, 191],
1655///         &[175, 170, 232, 233],
1656///         &[],
1657///         &[2, 35, 22, 217, 198, 114],
1658///         &[],
1659///         &[],
1660///         &[17, 32, 173, 114, 65, 121, 222, 25, 144, 148, 79],
1661///         &[115, 52, 73, 69, 137, 91, 153, 178],
1662///         &[],
1663///         &[112, 34, 95],
1664///         &[],
1665///         &[106, 167, 197, 130, 168],
1666///         &[122, 207, 172, 177, 86, 150, 221, 218, 101]
1667///     ]
1668/// );
1669/// ```
1670#[inline]
1671pub fn random_unique_vecs<I: Iterator>(
1672    seed: Seed,
1673    xs_gen: &dyn Fn(Seed) -> I,
1674    mean_length_numerator: u64,
1675    mean_length_denominator: u64,
1676) -> RandomUniqueVecs<I::Item, GeometricRandomNaturalValues<u64>, I>
1677where
1678    I::Item: Eq + Hash,
1679{
1680    random_unique_vecs_from_length_iterator(
1681        seed,
1682        &|seed_2| {
1683            geometric_random_unsigneds(seed_2, mean_length_numerator, mean_length_denominator)
1684        },
1685        xs_gen,
1686    )
1687}
1688
1689/// Generates random [`Vec`]s with a minimum length, using elements from an iterator, where the
1690/// [`Vec`]s have no repeated elements.
1691///
1692/// Strictly speaking, the input iterator must generate infinitely many distinct elements. In
1693/// practice it only needs to generate $k$ distinct elements, where $k$ is the largest length
1694/// actually sampled from the geometric distribution. For example, if `mean_length_numerator /
1695/// mean_length_denominator` is significantly lower than 256, then it's ok to use
1696/// `random_unsigneds::<u8>`.
1697///
1698/// `xs_gen` must be infinite.
1699///
1700/// # Expected complexity per iteration
1701/// $T(i) = O(m T^\prime(i))$
1702///
1703/// $M(i) = O(m M^\prime(i))$
1704///
1705/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
1706/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`, and $m$ is
1707/// `mean_length_numerator / mean_length_denominator`.
1708///
1709/// If `xs` can repeat values, extra draws are needed to reach the required number of distinct
1710/// elements, and an iteration fails to terminate if fewer distinct values are reachable than the
1711/// requested length.
1712///
1713/// # Panics
1714/// Panics if `mean_length_numerator` or `mean_length_denominator` are zero, if their ratio is less
1715/// than or equal to `min_length`, or if they are too large and manipulating them leads to
1716/// arithmetic overflow.
1717///
1718/// # Examples
1719/// ```
1720/// use itertools::Itertools;
1721/// use malachite_base::num::random::random_primitive_ints;
1722/// use malachite_base::random::EXAMPLE_SEED;
1723/// use malachite_base::vecs::random::random_unique_vecs_min_length;
1724///
1725/// let xs = random_unique_vecs_min_length(EXAMPLE_SEED, 2, &random_primitive_ints::<u8>, 6, 1);
1726/// let values = xs.take(20).collect_vec();
1727/// assert_eq!(
1728///     values.iter().map(Vec::as_slice).collect_vec().as_slice(),
1729///     &[
1730///         &[85, 11][..],
1731///         &[136, 200, 235, 134, 203, 223, 38, 217, 177, 162, 32, 166, 234, 30, 218, 90],
1732///         &[106, 9, 216, 204, 151, 213],
1733///         &[97, 253, 78, 91, 39, 191],
1734///         &[175, 170, 232],
1735///         &[233, 2],
1736///         &[35, 22, 217, 198, 114, 17, 32],
1737///         &[173, 114, 65, 121],
1738///         &[222, 173, 25, 144, 148, 79],
1739///         &[115, 52],
1740///         &[73, 69, 137, 91, 153, 178, 112, 34],
1741///         &[95, 106],
1742///         &[167, 197],
1743///         &[130, 168, 122, 207, 172, 177, 86, 150, 221, 218, 101, 115, 74],
1744///         &[9, 123, 109, 52, 201, 159, 247, 250, 48, 133],
1745///         &[235, 196],
1746///         &[40, 97, 104, 68, 190],
1747///         &[216, 7],
1748///         &[216, 157, 43, 112, 217, 24, 11],
1749///         &[103, 211, 84, 135, 55, 29, 206, 89, 65, 191, 51]
1750///     ]
1751/// );
1752/// ```
1753#[inline]
1754pub fn random_unique_vecs_min_length<I: Iterator>(
1755    seed: Seed,
1756    min_length: u64,
1757    xs_gen: &dyn Fn(Seed) -> I,
1758    mean_length_numerator: u64,
1759    mean_length_denominator: u64,
1760) -> RandomUniqueVecs<I::Item, GeometricRandomNaturalValues<u64>, I>
1761where
1762    I::Item: Eq + Hash,
1763{
1764    random_unique_vecs_from_length_iterator(
1765        seed,
1766        &|seed_2| {
1767            geometric_random_unsigned_inclusive_range(
1768                seed_2,
1769                min_length,
1770                u64::MAX,
1771                mean_length_numerator,
1772                mean_length_denominator,
1773            )
1774        },
1775        xs_gen,
1776    )
1777}
1778
1779/// Generates random [`Vec`]s with lengths in $[a, b)$, using elements from an iterator, where the
1780/// [`Vec`]s have no repeated elements.
1781///
1782/// The lengths of the [`Vec`]s are sampled from a uniform distribution on $[a, b)$. $a$ must be
1783/// less than $b$.
1784///
1785/// The input iterator must generate at least $b$ distinct elements.
1786///
1787/// `xs_gen` must be infinite.
1788///
1789/// # Expected complexity per iteration
1790/// $T(i) = O(b T^\prime(i))$
1791///
1792/// $M(i) = O(b M^\prime(i))$
1793///
1794/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
1795/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`, and $b$ is
1796/// `b`.
1797///
1798/// If `xs` can repeat values, extra draws are needed to reach the required number of distinct
1799/// elements, and an iteration fails to terminate if fewer distinct values are reachable than the
1800/// requested length.
1801///
1802/// # Panics
1803/// Panics if $a \geq b$.
1804///
1805/// # Examples
1806/// ```
1807/// use itertools::Itertools;
1808/// use malachite_base::num::random::random_primitive_ints;
1809/// use malachite_base::random::EXAMPLE_SEED;
1810/// use malachite_base::vecs::random::random_unique_vecs_length_range;
1811///
1812/// let xs = random_unique_vecs_length_range(EXAMPLE_SEED, 2, 5, &random_primitive_ints::<u8>);
1813/// let values = xs.take(20).collect_vec();
1814/// assert_eq!(
1815///     values.iter().map(Vec::as_slice).collect_vec().as_slice(),
1816///     &[
1817///         &[85, 11, 136][..],
1818///         &[200, 235, 134, 203],
1819///         &[223, 38, 235],
1820///         &[217, 177, 162, 32],
1821///         &[166, 234, 30, 218],
1822///         &[90, 106, 9],
1823///         &[216, 204],
1824///         &[151, 213, 97],
1825///         &[253, 78],
1826///         &[91, 39, 191, 175],
1827///         &[170, 232, 233, 2],
1828///         &[35, 22, 217],
1829///         &[198, 114, 17, 32],
1830///         &[173, 114, 65],
1831///         &[121, 222, 173, 25],
1832///         &[144, 148, 79, 115],
1833///         &[52, 73, 69, 137],
1834///         &[91, 153],
1835///         &[178, 112, 34, 95],
1836///         &[106, 167]
1837///     ]
1838/// );
1839/// ```
1840#[inline]
1841pub fn random_unique_vecs_length_range<I: Iterator>(
1842    seed: Seed,
1843    a: u64,
1844    b: u64,
1845    xs_gen: &dyn Fn(Seed) -> I,
1846) -> RandomUniqueVecs<I::Item, RandomUnsignedRange<u64>, I>
1847where
1848    I::Item: Eq + Hash,
1849{
1850    random_unique_vecs_from_length_iterator(
1851        seed,
1852        &|seed_2| random_unsigned_range(seed_2, a, b),
1853        xs_gen,
1854    )
1855}
1856
1857/// Generates random [`Vec`]s with lengths in $[a, b]$, using elements from an iterator, where the
1858/// [`Vec`]s have no repeated elements.
1859///
1860/// The lengths of the [`Vec`]s are sampled from a uniform distribution on $[a, b]$. $a$ must be
1861/// less than or equal to $b$.
1862///
1863/// The input iterator must generate at least $b$ distinct elements.
1864///
1865/// `xs_gen` must be infinite.
1866///
1867/// # Expected complexity per iteration
1868/// $T(i) = O(b T^\prime(i))$
1869///
1870/// $M(i) = O(b M^\prime(i))$
1871///
1872/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
1873/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`, and $b$ is
1874/// `b`.
1875///
1876/// If `xs` can repeat values, extra draws are needed to reach the required number of distinct
1877/// elements, and an iteration fails to terminate if fewer distinct values are reachable than the
1878/// requested length.
1879///
1880/// # Panics
1881/// Panics if $a > b$.
1882///
1883/// # Examples
1884/// ```
1885/// use itertools::Itertools;
1886/// use malachite_base::num::random::random_primitive_ints;
1887/// use malachite_base::random::EXAMPLE_SEED;
1888/// use malachite_base::vecs::random::random_unique_vecs_length_inclusive_range;
1889///
1890/// let xs =
1891///     random_unique_vecs_length_inclusive_range(EXAMPLE_SEED, 2, 4, &random_primitive_ints::<u8>);
1892/// let values = xs.take(20).collect_vec();
1893/// assert_eq!(
1894///     values.iter().map(Vec::as_slice).collect_vec().as_slice(),
1895///     &[
1896///         &[85, 11, 136][..],
1897///         &[200, 235, 134, 203],
1898///         &[223, 38, 235],
1899///         &[217, 177, 162, 32],
1900///         &[166, 234, 30, 218],
1901///         &[90, 106, 9],
1902///         &[216, 204],
1903///         &[151, 213, 97],
1904///         &[253, 78],
1905///         &[91, 39, 191, 175],
1906///         &[170, 232, 233, 2],
1907///         &[35, 22, 217],
1908///         &[198, 114, 17, 32],
1909///         &[173, 114, 65],
1910///         &[121, 222, 173, 25],
1911///         &[144, 148, 79, 115],
1912///         &[52, 73, 69, 137],
1913///         &[91, 153],
1914///         &[178, 112, 34, 95],
1915///         &[106, 167]
1916///     ]
1917/// );
1918/// ```
1919#[inline]
1920pub fn random_unique_vecs_length_inclusive_range<I: Iterator>(
1921    seed: Seed,
1922    a: u64,
1923    b: u64,
1924    xs_gen: &dyn Fn(Seed) -> I,
1925) -> RandomUniqueVecs<I::Item, RandomUnsignedInclusiveRange<u64>, I>
1926where
1927    I::Item: Eq + Hash,
1928{
1929    random_unique_vecs_from_length_iterator(
1930        seed,
1931        &|seed_2| random_unsigned_inclusive_range(seed_2, a, b),
1932        xs_gen,
1933    )
1934}