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/// Generates random [`Vec`]s of a given length whose last element comes from a different iterator
710/// than the rest.
711///
712/// This `struct` is created by [`random_vecs_with_last_fixed_length`]; see its documentation for
713/// more.
714#[derive(Clone, Debug)]
715pub struct RandomFixedLengthVecsWithLast<T, I: Iterator<Item = T>, J: Iterator<Item = T>> {
716 len: u64,
717 xs: I,
718 ys: J,
719}
720
721impl<T, I: Iterator<Item = T>, J: Iterator<Item = T>> Iterator
722 for RandomFixedLengthVecsWithLast<T, I, J>
723{
724 type Item = Vec<T>;
725
726 fn next(&mut self) -> Option<Vec<T>> {
727 Some(next_with_last(self.len, &mut self.xs, &mut self.ys))
728 }
729}
730
731// Takes one `Vec` of a given length, its first elements from `xs` and its last from `ys`.
732//
733// A length of zero takes nothing from either, since the empty `Vec` has no last element. Both
734// iterators must be infinite, as they must be everywhere else in this module.
735fn next_with_last<T, I: Iterator<Item = T>, J: Iterator<Item = T>>(
736 len: u64,
737 xs: &mut I,
738 ys: &mut J,
739) -> Vec<T> {
740 if len == 0 {
741 return Vec::new();
742 }
743 let mut out: Vec<T> = xs.take(usize::exact_from(len - 1)).collect();
744 out.push(ys.next().unwrap());
745 out
746}
747
748/// Randomly generates length-$n$ [`Vec`]s whose last element is drawn from a different iterator
749/// than the rest.
750///
751/// The first $n-1$ elements come from `xs` and the last comes from `ys`. If `len` is 0 there is no
752/// last element, and the output is the empty [`Vec`], repeated.
753///
754/// The probability of a particular [`Vec`] being generated is the product of the probabilities of
755/// each of its elements.
756///
757/// `xs` and `ys` must be infinite.
758///
759/// # Worst-case complexity per iteration
760/// $T(i) = O(n T^\prime(i))$
761///
762/// $M(i) = O(n M^\prime(i))$
763///
764/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
765/// $M^\prime$ are the time and memory functions of `xs` and `ys`, and $n$ is `len`.
766///
767/// # Examples
768/// ```
769/// use itertools::Itertools;
770/// use malachite_base::num::random::random_unsigned_inclusive_range;
771/// use malachite_base::random::EXAMPLE_SEED;
772/// use malachite_base::vecs::random::random_vecs_with_last_fixed_length;
773///
774/// let xs = random_unsigned_inclusive_range::<u32>(EXAMPLE_SEED.fork("xs"), 0, 9);
775/// let ys = random_unsigned_inclusive_range::<u32>(EXAMPLE_SEED.fork("ys"), 90, 99);
776/// let xss = random_vecs_with_last_fixed_length(3, xs, ys)
777/// .take(5)
778/// .collect_vec();
779/// assert_eq!(
780/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
781/// &[&[5, 5, 92][..], &[0, 8, 96], &[8, 8, 98], &[6, 8, 96], &[6, 2, 98]]
782/// );
783/// ```
784#[inline]
785pub const fn random_vecs_with_last_fixed_length<T, I: Iterator<Item = T>, J: Iterator<Item = T>>(
786 len: u64,
787 xs: I,
788 ys: J,
789) -> RandomFixedLengthVecsWithLast<T, I, J> {
790 RandomFixedLengthVecsWithLast { len, xs, ys }
791}
792
793/// Generates random [`Vec`]s whose last element comes from a different iterator than the rest, and
794/// with lengths from a third iterator.
795///
796/// This `struct` is created by [`random_vecs_with_last_from_length_iterator`]; see its
797/// documentation for more.
798#[derive(Clone, Debug)]
799pub struct RandomVecsWithLast<
800 T,
801 I: Iterator<Item = u64>,
802 J: Iterator<Item = T>,
803 K: Iterator<Item = T>,
804> {
805 lengths: I,
806 xs: J,
807 ys: K,
808}
809
810impl<T, I: Iterator<Item = u64>, J: Iterator<Item = T>, K: Iterator<Item = T>> Iterator
811 for RandomVecsWithLast<T, I, J, K>
812{
813 type Item = Vec<T>;
814
815 fn next(&mut self) -> Option<Vec<T>> {
816 let len = self.lengths.next().unwrap();
817 Some(next_with_last(len, &mut self.xs, &mut self.ys))
818 }
819}
820
821/// Generates random [`Vec`]s whose last element is drawn from a different iterator than the rest,
822/// and with lengths from a third iterator.
823///
824/// A [`Vec`] of length $n \geq 1$ has its first $n-1$ elements from `xs` and its last from `ys`;
825/// the empty [`Vec`], which has no last element, takes nothing from either.
826///
827/// The probability of a particular [`Vec`] being generated is the product of the probabilities of
828/// each of its elements, multiplied by the probability of its length being generated.
829///
830/// `lengths`, `xs`, and `ys` must be infinite.
831///
832/// # Worst-case complexity per iteration
833/// $T(i) = O(T^{\prime\prime}(i) + \ell T^\prime(i))$
834///
835/// $M(i) = O(M^{\prime\prime}(i) + \ell M^\prime(i))$
836///
837/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
838/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen` and `ys_gen`,
839/// $T^{\prime\prime}$ and $M^{\prime\prime}$ are the time and memory functions of `lengths`, and
840/// $\ell$ is the $i$th generated length.
841///
842/// # Examples
843/// ```
844/// use itertools::Itertools;
845/// use malachite_base::num::random::random_unsigned_inclusive_range;
846/// use malachite_base::random::EXAMPLE_SEED;
847/// use malachite_base::vecs::random::random_vecs_with_last_from_length_iterator;
848/// use malachite_base::vecs::random_values_from_vec;
849///
850/// let xss = random_vecs_with_last_from_length_iterator(
851/// EXAMPLE_SEED,
852/// &|seed| random_values_from_vec(seed, vec![0, 1, 2]),
853/// &|seed| random_unsigned_inclusive_range::<u32>(seed, 0, 9),
854/// &|seed| random_unsigned_inclusive_range::<u32>(seed, 90, 99),
855/// )
856/// .take(8)
857/// .collect_vec();
858/// assert_eq!(
859/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
860/// &[&[92][..], &[5, 96], &[98], &[5, 96], &[0, 98], &[92], &[], &[94]]
861/// );
862/// ```
863#[inline]
864pub fn random_vecs_with_last_from_length_iterator<
865 T,
866 I: Iterator<Item = u64>,
867 J: Iterator<Item = T>,
868 K: Iterator<Item = T>,
869>(
870 seed: Seed,
871 lengths_gen: &dyn Fn(Seed) -> I,
872 xs_gen: &dyn Fn(Seed) -> J,
873 ys_gen: &dyn Fn(Seed) -> K,
874) -> RandomVecsWithLast<T, I, J, K> {
875 RandomVecsWithLast {
876 lengths: lengths_gen(seed.fork("lengths")),
877 xs: xs_gen(seed.fork("xs")),
878 ys: ys_gen(seed.fork("ys")),
879 }
880}
881
882/// Randomly generates [`Vec`]s whose last element is drawn from a different iterator than the rest.
883///
884/// A [`Vec`] of length $n \geq 1$ has its first $n-1$ elements from `xs` and its last from `ys`;
885/// the empty [`Vec`], which has no last element, takes nothing from either.
886///
887/// The lengths of the [`Vec`]s are sampled from a geometric distribution with a specified mean $m$,
888/// equal to `mean_length_numerator / mean_length_denominator`. $m$ must be greater than 0.
889///
890/// `xs` and `ys` must be infinite.
891///
892/// # Worst-case complexity per iteration
893/// $T(i) = O(\ell T^\prime(i))$
894///
895/// $M(i) = O(\ell M^\prime(i))$
896///
897/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
898/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen` and `ys_gen`,
899/// and $\ell$ is the $i$th generated length.
900///
901/// # Panics
902/// Panics if `mean_length_numerator` or `mean_length_denominator` are zero, or if their ratio is
903/// greater than or equal to $2^{64}$.
904///
905/// # Examples
906/// ```
907/// use itertools::Itertools;
908/// use malachite_base::num::random::random_unsigned_inclusive_range;
909/// use malachite_base::random::EXAMPLE_SEED;
910/// use malachite_base::vecs::random::random_vecs_with_last;
911///
912/// let xss = random_vecs_with_last(
913/// EXAMPLE_SEED,
914/// &|seed| random_unsigned_inclusive_range::<u32>(seed, 0, 9),
915/// &|seed| random_unsigned_inclusive_range::<u32>(seed, 90, 99),
916/// 2,
917/// 1,
918/// )
919/// .take(8)
920/// .collect_vec();
921/// assert_eq!(
922/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
923/// &[
924/// &[5, 5, 0, 8, 8, 92][..],
925/// &[96],
926/// &[8, 6, 8, 6, 2, 9, 1, 98],
927/// &[96],
928/// &[2, 0, 2, 6, 1, 5, 6, 9, 0, 8, 7, 9, 5, 98],
929/// &[],
930/// &[1, 6, 4, 5, 92],
931/// &[7, 2, 8, 94]
932/// ]
933/// );
934/// ```
935#[inline]
936pub fn random_vecs_with_last<T, I: Iterator<Item = T>, J: Iterator<Item = T>>(
937 seed: Seed,
938 xs_gen: &dyn Fn(Seed) -> I,
939 ys_gen: &dyn Fn(Seed) -> J,
940 mean_length_numerator: u64,
941 mean_length_denominator: u64,
942) -> RandomVecsWithLast<T, GeometricRandomNaturalValues<u64>, I, J> {
943 random_vecs_with_last_from_length_iterator(
944 seed,
945 &|seed_2| {
946 geometric_random_unsigneds(seed_2, mean_length_numerator, mean_length_denominator)
947 },
948 xs_gen,
949 ys_gen,
950 )
951}
952
953/// Randomly generates [`Vec`]s with a minimum length, whose last element is drawn from a different
954/// iterator than the rest.
955///
956/// The lengths of the [`Vec`]s are sampled from a geometric distribution with a specified mean $m$,
957/// equal to `mean_length_numerator / mean_length_denominator`. $m$ must be greater than
958/// `min_length`.
959///
960/// `xs` and `ys` must be infinite.
961///
962/// # Worst-case complexity per iteration
963/// $T(i) = O(\ell T^\prime(i))$
964///
965/// $M(i) = O(\ell M^\prime(i))$
966///
967/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
968/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen` and `ys_gen`,
969/// and $\ell$ is the $i$th generated length.
970///
971/// # Panics
972/// Panics if `mean_length_numerator` or `mean_length_denominator` are zero, or if their ratio is
973/// less than or equal to `min_length`.
974///
975/// # Examples
976/// ```
977/// use itertools::Itertools;
978/// use malachite_base::num::random::random_unsigned_inclusive_range;
979/// use malachite_base::random::EXAMPLE_SEED;
980/// use malachite_base::vecs::random::random_vecs_with_last_min_length;
981///
982/// let xss = random_vecs_with_last_min_length(
983/// EXAMPLE_SEED,
984/// 2,
985/// &|seed| random_unsigned_inclusive_range::<u32>(seed, 0, 9),
986/// &|seed| random_unsigned_inclusive_range::<u32>(seed, 90, 99),
987/// 4,
988/// 1,
989/// )
990/// .take(5)
991/// .collect_vec();
992/// assert_eq!(
993/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
994/// &[
995/// &[5, 5, 0, 8, 8, 8, 6, 92][..],
996/// &[8, 6, 96],
997/// &[2, 9, 1, 2, 0, 2, 6, 1, 5, 98],
998/// &[6, 9, 96],
999/// &[0, 8, 7, 9, 5, 1, 6, 4, 5, 7, 2, 8, 9, 2, 0, 98]
1000/// ]
1001/// );
1002/// ```
1003#[inline]
1004pub fn random_vecs_with_last_min_length<T, I: Iterator<Item = T>, J: Iterator<Item = T>>(
1005 seed: Seed,
1006 min_length: u64,
1007 xs_gen: &dyn Fn(Seed) -> I,
1008 ys_gen: &dyn Fn(Seed) -> J,
1009 mean_length_numerator: u64,
1010 mean_length_denominator: u64,
1011) -> RandomVecsWithLast<T, GeometricRandomNaturalValues<u64>, I, J> {
1012 random_vecs_with_last_from_length_iterator(
1013 seed,
1014 &|seed_2| {
1015 geometric_random_unsigned_inclusive_range(
1016 seed_2,
1017 min_length,
1018 u64::MAX,
1019 mean_length_numerator,
1020 mean_length_denominator,
1021 )
1022 },
1023 xs_gen,
1024 ys_gen,
1025 )
1026}
1027
1028/// Randomly generates [`Vec`]s with lengths in $[a, b)$, whose last element is drawn from a
1029/// different iterator than the rest.
1030///
1031/// The lengths of the [`Vec`]s are sampled from a uniform distribution on $[a, b)$. $a$ must be
1032/// less than $b$.
1033///
1034/// `xs` and `ys` must be infinite.
1035///
1036/// # Worst-case complexity per iteration
1037/// $T(i) = O(\ell T^\prime(i))$
1038///
1039/// $M(i) = O(\ell M^\prime(i))$
1040///
1041/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
1042/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen` and `ys_gen`,
1043/// and $\ell$ is the $i$th generated length.
1044///
1045/// # Panics
1046/// Panics if $a \geq b$.
1047///
1048/// # Examples
1049/// ```
1050/// use itertools::Itertools;
1051/// use malachite_base::num::random::random_unsigned_inclusive_range;
1052/// use malachite_base::random::EXAMPLE_SEED;
1053/// use malachite_base::vecs::random::random_vecs_with_last_length_range;
1054///
1055/// let xss = random_vecs_with_last_length_range(
1056/// EXAMPLE_SEED,
1057/// 1,
1058/// 3,
1059/// &|seed| random_unsigned_inclusive_range::<u32>(seed, 0, 9),
1060/// &|seed| random_unsigned_inclusive_range::<u32>(seed, 90, 99),
1061/// )
1062/// .take(5)
1063/// .collect_vec();
1064/// assert_eq!(
1065/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
1066/// &[&[5, 92][..], &[96], &[5, 98], &[0, 96], &[98]]
1067/// );
1068/// ```
1069#[inline]
1070pub fn random_vecs_with_last_length_range<T, I: Iterator<Item = T>, J: Iterator<Item = T>>(
1071 seed: Seed,
1072 a: u64,
1073 b: u64,
1074 xs_gen: &dyn Fn(Seed) -> I,
1075 ys_gen: &dyn Fn(Seed) -> J,
1076) -> RandomVecsWithLast<T, RandomUnsignedRange<u64>, I, J> {
1077 random_vecs_with_last_from_length_iterator(
1078 seed,
1079 &|seed_2| random_unsigned_range(seed_2, a, b),
1080 xs_gen,
1081 ys_gen,
1082 )
1083}
1084
1085/// Randomly generates [`Vec`]s with lengths in $[a, b]$, whose last element is drawn from a
1086/// different iterator than the rest.
1087///
1088/// The lengths of the [`Vec`]s are sampled from a uniform distribution on $[a, b]$. $a$ must be
1089/// less than or equal to $b$.
1090///
1091/// `xs` and `ys` must be infinite.
1092///
1093/// # Worst-case complexity per iteration
1094/// $T(i) = O(\ell T^\prime(i))$
1095///
1096/// $M(i) = O(\ell M^\prime(i))$
1097///
1098/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
1099/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen` and `ys_gen`,
1100/// and $\ell$ is the $i$th generated length.
1101///
1102/// # Panics
1103/// Panics if $a > b$.
1104///
1105/// # Examples
1106/// ```
1107/// use itertools::Itertools;
1108/// use malachite_base::num::random::random_unsigned_inclusive_range;
1109/// use malachite_base::random::EXAMPLE_SEED;
1110/// use malachite_base::vecs::random::random_vecs_with_last_length_inclusive_range;
1111///
1112/// let xss = random_vecs_with_last_length_inclusive_range(
1113/// EXAMPLE_SEED,
1114/// 1,
1115/// 2,
1116/// &|seed| random_unsigned_inclusive_range::<u32>(seed, 0, 9),
1117/// &|seed| random_unsigned_inclusive_range::<u32>(seed, 90, 99),
1118/// )
1119/// .take(5)
1120/// .collect_vec();
1121/// assert_eq!(
1122/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
1123/// &[&[5, 92][..], &[96], &[5, 98], &[0, 96], &[98]]
1124/// );
1125/// ```
1126#[inline]
1127pub fn random_vecs_with_last_length_inclusive_range<
1128 T,
1129 I: Iterator<Item = T>,
1130 J: Iterator<Item = T>,
1131>(
1132 seed: Seed,
1133 a: u64,
1134 b: u64,
1135 xs_gen: &dyn Fn(Seed) -> I,
1136 ys_gen: &dyn Fn(Seed) -> J,
1137) -> RandomVecsWithLast<T, RandomUnsignedInclusiveRange<u64>, I, J> {
1138 random_vecs_with_last_from_length_iterator(
1139 seed,
1140 &|seed_2| random_unsigned_inclusive_range(seed_2, a, b),
1141 xs_gen,
1142 ys_gen,
1143 )
1144}
1145
1146#[doc(hidden)]
1147#[derive(Clone, Debug)]
1148pub struct RandomOrderedUniqueVecsLength2<I: Iterator>
1149where
1150 I::Item: Ord,
1151{
1152 xs: I,
1153}
1154
1155impl<I: Iterator> Iterator for RandomOrderedUniqueVecsLength2<I>
1156where
1157 I::Item: Ord,
1158{
1159 type Item = Vec<I::Item>;
1160
1161 #[inline]
1162 fn next(&mut self) -> Option<Vec<I::Item>> {
1163 let mut out = Vec::with_capacity(2);
1164 loop {
1165 let x = self.xs.next().unwrap();
1166 if out.is_empty() {
1167 out.push(x);
1168 } else {
1169 match x.cmp(&out[0]) {
1170 Equal => {}
1171 Greater => {
1172 out.push(x);
1173 break;
1174 }
1175 Less => {
1176 out.insert(0, x);
1177 break;
1178 }
1179 }
1180 }
1181 }
1182 Some(out)
1183 }
1184}
1185
1186#[doc(hidden)]
1187#[derive(Clone, Debug)]
1188pub struct RandomOrderedUniqueVecsFixedLengthGreaterThan2<I: Iterator>
1189where
1190 I::Item: Ord,
1191{
1192 xs: RandomBTreeSetsFixedLength<I>,
1193}
1194
1195impl<I: Iterator> Iterator for RandomOrderedUniqueVecsFixedLengthGreaterThan2<I>
1196where
1197 I::Item: Ord,
1198{
1199 type Item = Vec<I::Item>;
1200
1201 #[inline]
1202 fn next(&mut self) -> Option<Vec<I::Item>> {
1203 Some(self.xs.next().unwrap().into_iter().collect())
1204 }
1205}
1206
1207/// Generates random [`Vec`]s of a fixed length, where the [`Vec`]s have no repeated elements, and
1208/// the elements are in ascending order.
1209///
1210/// This `struct` is created by [`random_ordered_unique_vecs_fixed_length`]; see its documentation
1211/// for more.
1212#[derive(Clone, Debug)]
1213pub enum RandomOrderedUniqueVecsFixedLength<I: Iterator>
1214where
1215 I::Item: Ord,
1216{
1217 Zero,
1218 One(I),
1219 Two(RandomOrderedUniqueVecsLength2<I>),
1220 GreaterThan2(RandomOrderedUniqueVecsFixedLengthGreaterThan2<I>),
1221}
1222
1223impl<I: Iterator> Iterator for RandomOrderedUniqueVecsFixedLength<I>
1224where
1225 I::Item: Ord,
1226{
1227 type Item = Vec<I::Item>;
1228
1229 #[inline]
1230 fn next(&mut self) -> Option<Vec<I::Item>> {
1231 match self {
1232 Self::Zero => Some(vec![]),
1233 Self::One(xs) => xs.next().map(|x| vec![x]),
1234 Self::Two(xs) => xs.next(),
1235 Self::GreaterThan2(xs) => xs.next(),
1236 }
1237 }
1238}
1239
1240/// Randomly generates [`Vec`]s of a given length, where the [`Vec`]s have no repeated elements, and
1241/// the elements are in ascending order.
1242///
1243/// The input iterator must generate at least `len` distinct elements; otherwise, this iterator will
1244/// hang.
1245///
1246/// $$
1247/// P((x\_i)\_{i=0}^{n-1}) = n!\prod\_{i=0}^{n-1}P(x\_i).
1248/// $$
1249///
1250/// The above formula assumes that the [`Vec`] is valid, \emph{i.e.} its elements are strictly
1251/// increasing. The probability of an invalid [`Vec`] is zero.
1252///
1253/// If `len` is 0, the output consists of the empty list, repeated.
1254///
1255/// `xs` must be infinite.
1256///
1257/// # Expected complexity per iteration
1258/// $T(i) = O(\ell^2 + \ell T^\prime(i))$
1259///
1260/// $M(i) = O(\ell M^\prime(i))$
1261///
1262/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
1263/// $M^\prime$ are the time and memory functions of `xs`, and $\ell$ is `len`; sorted insertion is
1264/// quadratic in the length.
1265///
1266/// If `xs` can repeat values, extra draws are needed to reach the required number of distinct
1267/// elements, and an iteration fails to terminate if fewer distinct values are reachable than the
1268/// requested length.
1269///
1270/// # Expected complexity per iteration
1271/// $T(i) = O(m^2 + m T^\prime(i))$
1272///
1273/// $M(i) = O(m M^\prime(i))$
1274///
1275/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
1276/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`, and $m$ is
1277/// `mean_length_numerator / mean_length_denominator`.
1278///
1279/// If `xs` can repeat values, extra draws are needed to reach the required number of distinct
1280/// elements, and an iteration fails to terminate if fewer distinct values are reachable than the
1281/// requested length.
1282///
1283/// # Examples
1284/// ```
1285/// use itertools::Itertools;
1286/// use malachite_base::num::random::random_unsigned_inclusive_range;
1287/// use malachite_base::random::EXAMPLE_SEED;
1288/// use malachite_base::vecs::random::random_ordered_unique_vecs_fixed_length;
1289///
1290/// let xss = random_ordered_unique_vecs_fixed_length(
1291/// 2,
1292/// random_unsigned_inclusive_range::<u32>(EXAMPLE_SEED, 1, 100),
1293/// )
1294/// .take(10)
1295/// .collect_vec();
1296/// assert_eq!(
1297/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
1298/// &[
1299/// &[24, 95],
1300/// &[71, 99],
1301/// &[53, 93],
1302/// &[34, 85],
1303/// &[2, 48],
1304/// &[11, 55],
1305/// &[18, 48],
1306/// &[90, 93],
1307/// &[67, 93],
1308/// &[93, 95]
1309/// ]
1310/// );
1311/// ```
1312#[inline]
1313pub fn random_ordered_unique_vecs_fixed_length<I: Iterator>(
1314 len: u64,
1315 xs: I,
1316) -> RandomOrderedUniqueVecsFixedLength<I>
1317where
1318 I::Item: Ord,
1319{
1320 match len {
1321 0 => RandomOrderedUniqueVecsFixedLength::Zero,
1322 1 => RandomOrderedUniqueVecsFixedLength::One(xs),
1323 2 => RandomOrderedUniqueVecsFixedLength::Two(RandomOrderedUniqueVecsLength2 { xs }),
1324 len => RandomOrderedUniqueVecsFixedLength::GreaterThan2(
1325 RandomOrderedUniqueVecsFixedLengthGreaterThan2 {
1326 xs: random_b_tree_sets_fixed_length(len, xs),
1327 },
1328 ),
1329 }
1330}
1331
1332/// Generates random [`Vec`]s with lengths from an iterator, where the [`Vec`]s have no repeated
1333/// elements, and the elements are in ascending order.
1334#[derive(Clone, Debug)]
1335pub struct RandomOrderedUniqueVecs<T: Ord, I: Iterator<Item = u64>, J: Iterator<Item = T>> {
1336 xs: RandomBTreeSets<T, I, J>,
1337}
1338
1339impl<T: Ord, I: Iterator<Item = u64>, J: Iterator<Item = T>> Iterator
1340 for RandomOrderedUniqueVecs<T, I, J>
1341{
1342 type Item = Vec<T>;
1343
1344 #[inline]
1345 fn next(&mut self) -> Option<Vec<T>> {
1346 Some(self.xs.next().unwrap().into_iter().collect())
1347 }
1348}
1349
1350/// Generates random [`Vec`]s using elements from an iterator and with lengths from another
1351/// iterator, where the [`Vec`]s have no repeated elements, and the elements are in ascending order.
1352///
1353/// The input iterator must generate at least many distinct elements as any number generated by the
1354/// lengths iterator; otherwise, this iterator will hang.
1355///
1356/// $$
1357/// P((x\_i)\_{i=0}^{n-1}) = n!P(n)\prod\_{i=0}^{n-1}P(x\_i).
1358/// $$
1359///
1360/// The above formula assumes that the [`Vec`] is valid, \emph{i.e.} its elements are strictly
1361/// increasing. The probability of an invalid [`Vec`] is zero.
1362///
1363/// `lengths` and `xs` must be infinite.
1364///
1365/// # Expected complexity per iteration
1366/// $T(i) = O(T^{\prime\prime}(i) + \ell^2 + \ell T^\prime(i))$
1367///
1368/// $M(i) = O(M^{\prime\prime}(i) + \ell M^\prime(i))$
1369///
1370/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
1371/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`,
1372/// $T^{\prime\prime}$ and $M^{\prime\prime}$ are the time and memory functions of `lengths`, and
1373/// $\ell$ is the $i$th generated length.
1374///
1375/// If `xs` can repeat values, extra draws are needed to reach the required number of distinct
1376/// elements, and an iteration fails to terminate if fewer distinct values are reachable than the
1377/// requested length.
1378///
1379/// # Examples
1380/// ```
1381/// use itertools::Itertools;
1382/// use malachite_base::num::random::random_primitive_ints;
1383/// use malachite_base::random::EXAMPLE_SEED;
1384/// use malachite_base::vecs::random::random_ordered_unique_vecs_from_length_iterator;
1385/// use malachite_base::vecs::random_values_from_vec;
1386///
1387/// let xs = random_ordered_unique_vecs_from_length_iterator(
1388/// EXAMPLE_SEED,
1389/// &|seed| random_values_from_vec(seed, vec![0, 2, 4]),
1390/// &random_primitive_ints::<u8>,
1391/// );
1392/// let values = xs.take(20).collect_vec();
1393/// assert_eq!(
1394/// values.iter().map(Vec::as_slice).collect_vec().as_slice(),
1395/// &[
1396/// &[11, 85][..],
1397/// &[134, 136, 200, 235],
1398/// &[203, 223],
1399/// &[38, 177, 217, 235],
1400/// &[32, 162, 166, 234],
1401/// &[30, 218],
1402/// &[],
1403/// &[90, 106],
1404/// &[],
1405/// &[9, 151, 204, 216],
1406/// &[78, 97, 213, 253],
1407/// &[39, 91],
1408/// &[170, 175, 191, 232],
1409/// &[2, 233],
1410/// &[22, 35, 198, 217],
1411/// &[17, 32, 114, 173],
1412/// &[65, 114, 121, 222],
1413/// &[],
1414/// &[25, 144, 148, 173],
1415/// &[]
1416/// ]
1417/// );
1418/// ```
1419#[inline]
1420pub fn random_ordered_unique_vecs_from_length_iterator<
1421 T: Ord,
1422 I: Iterator<Item = u64>,
1423 J: Iterator<Item = T>,
1424>(
1425 seed: Seed,
1426 lengths_gen: &dyn Fn(Seed) -> I,
1427 xs_gen: &dyn Fn(Seed) -> J,
1428) -> RandomOrderedUniqueVecs<T, I, J> {
1429 RandomOrderedUniqueVecs {
1430 xs: random_b_tree_sets_from_length_iterator(seed, lengths_gen, xs_gen),
1431 }
1432}
1433
1434/// Generates random [`Vec`]s using elements from an iterator, where the [`Vec`]s have no repeated
1435/// elements, and the elements are in ascending order.
1436///
1437/// The lengths of the [`Vec`]s are sampled from a geometric distribution with a specified mean $m$,
1438/// equal to `mean_length_numerator / mean_length_denominator`. $m$ must be greater than 0.
1439///
1440/// Strictly speaking, the input iterator must generate infinitely many distinct elements. In
1441/// practice it only needs to generate $k$ distinct elements, where $k$ is the largest length
1442/// actually sampled from the geometric distribution. For example, if `mean_length_numerator /
1443/// mean_length_denominator` is significantly lower than 256, then it's ok to use
1444/// `random_unsigneds::<u8>`.
1445///
1446/// $$
1447/// P((x\_i)\_{i=0}^{n-1}) = n!P_g(n)\prod\_{i=0}^{n-1}P(x\_i),
1448/// $$
1449/// where $P_g(n)$ is the probability function described in [`geometric_random_unsigneds`].
1450///
1451/// `xs_gen` must be infinite.
1452///
1453/// # Expected complexity per iteration
1454/// $T(i) = O(m T^\prime(i))$
1455///
1456/// $M(i) = O(m M^\prime(i))$
1457///
1458/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
1459/// $M^\prime$ are the time and memory functions of `xs`, and $m$ is `mean_length_numerator /
1460/// mean_length_denominator`.
1461///
1462/// # Panics
1463/// Panics if `mean_length_numerator` or `mean_length_denominator` are zero, or, if after being
1464/// reduced to lowest terms, their sum is greater than or equal to $2^{64}$.
1465///
1466/// # Examples
1467/// ```
1468/// use itertools::Itertools;
1469/// use malachite_base::num::random::random_primitive_ints;
1470/// use malachite_base::random::EXAMPLE_SEED;
1471/// use malachite_base::vecs::random::random_ordered_unique_vecs;
1472///
1473/// let xs = random_ordered_unique_vecs(EXAMPLE_SEED, &random_primitive_ints::<u8>, 4, 1);
1474/// let values = xs.take(20).collect_vec();
1475/// assert_eq!(
1476/// values.iter().map(Vec::as_slice).collect_vec().as_slice(),
1477/// &[
1478/// &[][..],
1479/// &[11, 32, 38, 85, 134, 136, 162, 166, 177, 200, 203, 217, 223, 235],
1480/// &[30, 90, 218, 234],
1481/// &[9, 106, 204, 216],
1482/// &[151],
1483/// &[],
1484/// &[78, 91, 97, 213, 253],
1485/// &[39, 191],
1486/// &[170, 175, 232, 233],
1487/// &[],
1488/// &[2, 22, 35, 114, 198, 217],
1489/// &[],
1490/// &[],
1491/// &[17, 25, 32, 65, 79, 114, 121, 144, 148, 173, 222],
1492/// &[52, 69, 73, 91, 115, 137, 153, 178],
1493/// &[],
1494/// &[34, 95, 112],
1495/// &[],
1496/// &[106, 130, 167, 168, 197],
1497/// &[86, 101, 122, 150, 172, 177, 207, 218, 221]
1498/// ]
1499/// );
1500/// ```
1501#[inline]
1502pub fn random_ordered_unique_vecs<I: Iterator>(
1503 seed: Seed,
1504 xs_gen: &dyn Fn(Seed) -> I,
1505 mean_length_numerator: u64,
1506 mean_length_denominator: u64,
1507) -> RandomOrderedUniqueVecs<I::Item, GeometricRandomNaturalValues<u64>, I>
1508where
1509 I::Item: Ord,
1510{
1511 random_ordered_unique_vecs_from_length_iterator(
1512 seed,
1513 &|seed_2| {
1514 geometric_random_unsigneds(seed_2, mean_length_numerator, mean_length_denominator)
1515 },
1516 xs_gen,
1517 )
1518}
1519
1520/// Generates random [`Vec`]s with a minimum length, using elements from an iterator, where the
1521/// [`Vec`]s have no repeated elements, and the elements are in ascending order.
1522///
1523/// Strictly speaking, the input iterator must generate infinitely many distinct elements. In
1524/// practice it only needs to generate $k$ distinct elements, where $k$ is the largest length
1525/// actually sampled from the geometric distribution. For example, if `mean_length_numerator /
1526/// mean_length_denominator` is significantly lower than 256, then it's ok to use
1527/// `random_unsigneds::<u8>`.
1528///
1529/// $$
1530/// P((x\_i)\_{i=0}^{n-1}) = n!P_g(n)\prod\_{i=0}^{n-1}P(x\_i),
1531/// $$
1532/// where $P_g(n)$ is the probability function described in
1533/// [`geometric_random_unsigned_inclusive_range`], with $a$ equal to `min_length` and `b` to
1534/// `u64::MAX`.
1535///
1536/// `xs_gen` must be infinite.
1537///
1538/// # Expected complexity per iteration
1539/// $T(i) = O(m^2 + m T^\prime(i))$
1540///
1541/// $M(i) = O(m M^\prime(i))$
1542///
1543/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
1544/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`, and $m$ is
1545/// `mean_length_numerator / mean_length_denominator`.
1546///
1547/// If `xs` can repeat values, extra draws are needed to reach the required number of distinct
1548/// elements, and an iteration fails to terminate if fewer distinct values are reachable than the
1549/// requested length.
1550///
1551/// # Panics
1552/// Panics if `mean_length_numerator` or `mean_length_denominator` are zero, if their ratio is less
1553/// than or equal to `min_length`, or if they are too large and manipulating them leads to
1554/// arithmetic overflow.
1555///
1556/// # Examples
1557/// ```
1558/// use itertools::Itertools;
1559/// use malachite_base::num::random::random_primitive_ints;
1560/// use malachite_base::random::EXAMPLE_SEED;
1561/// use malachite_base::vecs::random::random_ordered_unique_vecs_min_length;
1562///
1563/// let xs =
1564/// random_ordered_unique_vecs_min_length(EXAMPLE_SEED, 2, &random_primitive_ints::<u8>, 6, 1);
1565/// let values = xs.take(20).collect_vec();
1566/// assert_eq!(
1567/// values.iter().map(Vec::as_slice).collect_vec().as_slice(),
1568/// &[
1569/// &[11, 85][..],
1570/// &[30, 32, 38, 90, 134, 136, 162, 166, 177, 200, 203, 217, 218, 223, 234, 235],
1571/// &[9, 106, 151, 204, 213, 216],
1572/// &[39, 78, 91, 97, 191, 253],
1573/// &[170, 175, 232],
1574/// &[2, 233],
1575/// &[17, 22, 32, 35, 114, 198, 217],
1576/// &[65, 114, 121, 173],
1577/// &[25, 79, 144, 148, 173, 222],
1578/// &[52, 115],
1579/// &[34, 69, 73, 91, 112, 137, 153, 178],
1580/// &[95, 106],
1581/// &[167, 197],
1582/// &[74, 86, 101, 115, 122, 130, 150, 168, 172, 177, 207, 218, 221],
1583/// &[9, 48, 52, 109, 123, 133, 159, 201, 247, 250],
1584/// &[196, 235],
1585/// &[40, 68, 97, 104, 190],
1586/// &[7, 216],
1587/// &[11, 24, 43, 112, 157, 216, 217],
1588/// &[29, 51, 55, 65, 84, 89, 103, 135, 191, 206, 211]
1589/// ]
1590/// );
1591/// ```
1592#[inline]
1593pub fn random_ordered_unique_vecs_min_length<I: Iterator>(
1594 seed: Seed,
1595 min_length: u64,
1596 xs_gen: &dyn Fn(Seed) -> I,
1597 mean_length_numerator: u64,
1598 mean_length_denominator: u64,
1599) -> RandomOrderedUniqueVecs<I::Item, GeometricRandomNaturalValues<u64>, I>
1600where
1601 I::Item: Ord,
1602{
1603 random_ordered_unique_vecs_from_length_iterator(
1604 seed,
1605 &|seed_2| {
1606 geometric_random_unsigned_inclusive_range(
1607 seed_2,
1608 min_length,
1609 u64::MAX,
1610 mean_length_numerator,
1611 mean_length_denominator,
1612 )
1613 },
1614 xs_gen,
1615 )
1616}
1617
1618/// Generates random [`Vec`]s with lengths in $[a, b)$, using elements from an iterator, where the
1619/// [`Vec`]s have no repeated elements, and the elements are in ascending order.
1620///
1621/// The lengths of the [`Vec`]s are sampled from a uniform distribution on $[a, b)$. $a$ must be
1622/// less than $b$.
1623///
1624/// The input iterator must generate at least $b$ distinct elements.
1625///
1626/// $$
1627/// P((x\_i)\_{i=0}^{n-1}, a, b) = \frac{n!}{b - a}\prod\_{i=0}^{n-1}P(x\_i).
1628/// $$
1629///
1630/// `xs_gen` must be infinite.
1631///
1632/// # Expected complexity per iteration
1633/// $T(i) = O(b^2 + b T^\prime(i))$
1634///
1635/// $M(i) = O(b M^\prime(i))$
1636///
1637/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
1638/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`, and $b$ is
1639/// `b`.
1640///
1641/// If `xs` can repeat values, extra draws are needed to reach the required number of distinct
1642/// elements, and an iteration fails to terminate if fewer distinct values are reachable than the
1643/// requested length.
1644///
1645/// # Panics
1646/// Panics if $a \geq b$.
1647///
1648/// # Examples
1649/// ```
1650/// use itertools::Itertools;
1651/// use malachite_base::num::random::random_primitive_ints;
1652/// use malachite_base::random::EXAMPLE_SEED;
1653/// use malachite_base::vecs::random::random_ordered_unique_vecs_length_range;
1654///
1655/// let xs =
1656/// random_ordered_unique_vecs_length_range(EXAMPLE_SEED, 2, 5, &random_primitive_ints::<u8>);
1657/// let values = xs.take(20).collect_vec();
1658/// assert_eq!(
1659/// values.iter().map(Vec::as_slice).collect_vec().as_slice(),
1660/// &[
1661/// &[11, 85, 136][..],
1662/// &[134, 200, 203, 235],
1663/// &[38, 223, 235],
1664/// &[32, 162, 177, 217],
1665/// &[30, 166, 218, 234],
1666/// &[9, 90, 106],
1667/// &[204, 216],
1668/// &[97, 151, 213],
1669/// &[78, 253],
1670/// &[39, 91, 175, 191],
1671/// &[2, 170, 232, 233],
1672/// &[22, 35, 217],
1673/// &[17, 32, 114, 198],
1674/// &[65, 114, 173],
1675/// &[25, 121, 173, 222],
1676/// &[79, 115, 144, 148],
1677/// &[52, 69, 73, 137],
1678/// &[91, 153],
1679/// &[34, 95, 112, 178],
1680/// &[106, 167]
1681/// ]
1682/// );
1683/// ```
1684#[inline]
1685pub fn random_ordered_unique_vecs_length_range<I: Iterator>(
1686 seed: Seed,
1687 a: u64,
1688 b: u64,
1689 xs_gen: &dyn Fn(Seed) -> I,
1690) -> RandomOrderedUniqueVecs<I::Item, RandomUnsignedRange<u64>, I>
1691where
1692 I::Item: Ord,
1693{
1694 random_ordered_unique_vecs_from_length_iterator(
1695 seed,
1696 &|seed_2| random_unsigned_range(seed_2, a, b),
1697 xs_gen,
1698 )
1699}
1700
1701/// Generates random [`Vec`]s with lengths in $[a, b]$, using elements from an iterator, where the
1702/// [`Vec`]s have no repeated elements, and the elements are in ascending order.
1703///
1704/// The lengths of the [`Vec`]s are sampled from a uniform distribution on $[a, b]$. $a$ must be
1705/// less than or equal to $b$.
1706///
1707/// The input iterator must generate at least $b$ distinct elements.
1708///
1709/// $$
1710/// P((x\_i)\_{i=0}^{n-1}, a, b) = \frac{n!}{b - a + 1}\prod\_{i=0}^{n-1}P(x\_i).
1711/// $$
1712///
1713/// `xs_gen` must be infinite.
1714///
1715/// # Expected complexity per iteration
1716/// $T(i) = O(b^2 + b T^\prime(i))$
1717///
1718/// $M(i) = O(b M^\prime(i))$
1719///
1720/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
1721/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`, and $b$ is
1722/// `b`.
1723///
1724/// If `xs` can repeat values, extra draws are needed to reach the required number of distinct
1725/// elements, and an iteration fails to terminate if fewer distinct values are reachable than the
1726/// requested length.
1727///
1728/// # Panics
1729/// Panics if $a > b$.
1730///
1731/// # Examples
1732/// ```
1733/// use itertools::Itertools;
1734/// use malachite_base::num::random::random_primitive_ints;
1735/// use malachite_base::random::EXAMPLE_SEED;
1736/// use malachite_base::vecs::random::random_ordered_unique_vecs_length_inclusive_range;
1737///
1738/// let xs = random_ordered_unique_vecs_length_inclusive_range(
1739/// EXAMPLE_SEED,
1740/// 2,
1741/// 4,
1742/// &random_primitive_ints::<u8>,
1743/// );
1744/// let values = xs.take(20).collect_vec();
1745/// assert_eq!(
1746/// values.iter().map(Vec::as_slice).collect_vec().as_slice(),
1747/// &[
1748/// &[11, 85, 136][..],
1749/// &[134, 200, 203, 235],
1750/// &[38, 223, 235],
1751/// &[32, 162, 177, 217],
1752/// &[30, 166, 218, 234],
1753/// &[9, 90, 106],
1754/// &[204, 216],
1755/// &[97, 151, 213],
1756/// &[78, 253],
1757/// &[39, 91, 175, 191],
1758/// &[2, 170, 232, 233],
1759/// &[22, 35, 217],
1760/// &[17, 32, 114, 198],
1761/// &[65, 114, 173],
1762/// &[25, 121, 173, 222],
1763/// &[79, 115, 144, 148],
1764/// &[52, 69, 73, 137],
1765/// &[91, 153],
1766/// &[34, 95, 112, 178],
1767/// &[106, 167]
1768/// ]
1769/// );
1770/// ```
1771#[inline]
1772pub fn random_ordered_unique_vecs_length_inclusive_range<I: Iterator>(
1773 seed: Seed,
1774 a: u64,
1775 b: u64,
1776 xs_gen: &dyn Fn(Seed) -> I,
1777) -> RandomOrderedUniqueVecs<I::Item, RandomUnsignedInclusiveRange<u64>, I>
1778where
1779 I::Item: Ord,
1780{
1781 random_ordered_unique_vecs_from_length_iterator(
1782 seed,
1783 &|seed_2| random_unsigned_inclusive_range(seed_2, a, b),
1784 xs_gen,
1785 )
1786}
1787
1788/// Generates random [`Vec`]s of a fixed length, where the elements are in ascending order and may
1789/// repeat.
1790///
1791/// This `struct` is created by [`random_ordered_vecs_fixed_length`]; see its documentation for
1792/// more.
1793#[derive(Clone, Debug)]
1794pub struct RandomOrderedVecsFixedLength<I: Iterator>
1795where
1796 I::Item: Ord,
1797{
1798 xs: RandomFixedLengthVecsFromSingle<I>,
1799}
1800
1801impl<I: Iterator> Iterator for RandomOrderedVecsFixedLength<I>
1802where
1803 I::Item: Ord,
1804{
1805 type Item = Vec<I::Item>;
1806
1807 #[inline]
1808 fn next(&mut self) -> Option<Vec<I::Item>> {
1809 let mut xs = self.xs.next().unwrap();
1810 xs.sort_unstable();
1811 Some(xs)
1812 }
1813}
1814
1815/// Randomly generates [`Vec`]s of a given length, where the elements are in ascending order and may
1816/// repeat.
1817///
1818/// Unlike the analogous generator for [`Vec`]s without repetitions, this one places no demand on
1819/// the element iterator: since elements may repeat, `len` draws always suffice.
1820///
1821/// $$
1822/// P((x\_i)\_{i=0}^{n-1}) = \frac{n!}{\prod\_j m\_j!} \prod\_{i=0}^{n-1}P(x\_i),
1823/// $$
1824/// where $m\_j$ is the number of times that the $j$th distinct value occurs. The formula assumes
1825/// that the [`Vec`] is valid, \emph{i.e.} its elements are nondecreasing; the probability of an
1826/// invalid [`Vec`] is zero. The multinomial coefficient counts the orderings of the elements that
1827/// sort to the same [`Vec`].
1828///
1829/// If `len` is 0, the output consists of the empty list, repeated.
1830///
1831/// Sorting gives every multiset a single representation, so two output [`Vec`]s are equal exactly
1832/// when they hold the same elements with the same multiplicities.
1833///
1834/// `xs` must be infinite.
1835///
1836/// # Expected complexity per iteration
1837/// $T(i) = O(n \log n + n T^\prime(i))$
1838///
1839/// $M(i) = O(n M^\prime(i))$
1840///
1841/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
1842/// $M^\prime$ are the time and memory functions of `xs`, and $n$ is `len`.
1843///
1844/// # Examples
1845/// ```
1846/// use itertools::Itertools;
1847/// use malachite_base::num::random::random_unsigned_inclusive_range;
1848/// use malachite_base::random::EXAMPLE_SEED;
1849/// use malachite_base::vecs::random::random_ordered_vecs_fixed_length;
1850///
1851/// let xss = random_ordered_vecs_fixed_length(
1852/// 2,
1853/// random_unsigned_inclusive_range::<u32>(EXAMPLE_SEED, 1, 100),
1854/// )
1855/// .take(10)
1856/// .collect_vec();
1857/// assert_eq!(
1858/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
1859/// &[
1860/// &[24, 95],
1861/// &[71, 99],
1862/// &[53, 93],
1863/// &[34, 85],
1864/// &[2, 48],
1865/// &[11, 55],
1866/// &[18, 48],
1867/// &[90, 93],
1868/// &[67, 93],
1869/// &[93, 95]
1870/// ]
1871/// );
1872/// ```
1873#[inline]
1874pub const fn random_ordered_vecs_fixed_length<I: Iterator>(
1875 len: u64,
1876 xs: I,
1877) -> RandomOrderedVecsFixedLength<I>
1878where
1879 I::Item: Ord,
1880{
1881 RandomOrderedVecsFixedLength {
1882 xs: random_vecs_fixed_length_from_single(len, xs),
1883 }
1884}
1885
1886/// Generates random [`Vec`]s with lengths from an iterator, where the elements are in ascending
1887/// order and may repeat.
1888///
1889/// This `struct` is created by [`random_ordered_vecs`] and similar functions; see their
1890/// documentation for more.
1891#[derive(Clone, Debug)]
1892pub struct RandomOrderedVecs<T: Ord, I: Iterator<Item = u64>, J: Iterator<Item = T>> {
1893 xs: RandomVecs<T, I, J>,
1894}
1895
1896impl<T: Ord, I: Iterator<Item = u64>, J: Iterator<Item = T>> Iterator
1897 for RandomOrderedVecs<T, I, J>
1898{
1899 type Item = Vec<T>;
1900
1901 #[inline]
1902 fn next(&mut self) -> Option<Vec<T>> {
1903 let mut xs = self.xs.next().unwrap();
1904 xs.sort_unstable();
1905 Some(xs)
1906 }
1907}
1908
1909/// Generates random [`Vec`]s using elements from an iterator and with lengths from another
1910/// iterator, where the elements are in ascending order and may repeat.
1911///
1912/// Unlike the analogous generator for [`Vec`]s without repetitions, this one places no demand on
1913/// the element iterator: since elements may repeat, any length is reachable.
1914///
1915/// $$
1916/// P((x\_i)\_{i=0}^{n-1}) = \frac{n!}{\prod\_j m\_j!} P(n) \prod\_{i=0}^{n-1}P(x\_i),
1917/// $$
1918/// where $m\_j$ is the number of times that the $j$th distinct value occurs. The formula assumes
1919/// that the [`Vec`] is valid, \emph{i.e.} its elements are nondecreasing; the probability of an
1920/// invalid [`Vec`] is zero.
1921///
1922/// Sorting gives every multiset a single representation, so two output [`Vec`]s are equal exactly
1923/// when they hold the same elements with the same multiplicities.
1924///
1925/// `lengths_gen` must produce only nonnegative values. `xs_gen` must be infinite.
1926///
1927/// # Expected complexity per iteration
1928/// $T(i) = O(n \log n + n T^\prime(i))$
1929///
1930/// $M(i) = O(n M^\prime(i))$
1931///
1932/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
1933/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`, and $n$ is
1934/// the mean length.
1935///
1936/// # Examples
1937/// ```
1938/// use itertools::Itertools;
1939/// use malachite_base::num::random::random_primitive_ints;
1940/// use malachite_base::random::EXAMPLE_SEED;
1941/// use malachite_base::vecs::random::random_ordered_vecs_from_length_iterator;
1942/// use malachite_base::vecs::random_values_from_vec;
1943///
1944/// let xs = random_ordered_vecs_from_length_iterator(
1945/// EXAMPLE_SEED,
1946/// &|seed| random_values_from_vec(seed, vec![0, 2, 4]),
1947/// &random_primitive_ints::<u8>,
1948/// );
1949/// let values = xs.take(20).collect_vec();
1950/// assert_eq!(
1951/// values.iter().map(Vec::as_slice).collect_vec().as_slice(),
1952/// &[
1953/// &[11, 85][..],
1954/// &[134, 136, 200, 235],
1955/// &[203, 223],
1956/// &[38, 177, 217, 235],
1957/// &[32, 162, 166, 234],
1958/// &[30, 218],
1959/// &[],
1960/// &[90, 106],
1961/// &[],
1962/// &[9, 151, 204, 216],
1963/// &[78, 97, 213, 253],
1964/// &[39, 91],
1965/// &[170, 175, 191, 232],
1966/// &[2, 233],
1967/// &[22, 35, 198, 217],
1968/// &[17, 32, 114, 173],
1969/// &[65, 114, 121, 222],
1970/// &[],
1971/// &[25, 144, 148, 173],
1972/// &[]
1973/// ]
1974/// );
1975/// ```
1976pub fn random_ordered_vecs_from_length_iterator<
1977 T: Ord,
1978 I: Iterator<Item = u64>,
1979 J: Iterator<Item = T>,
1980>(
1981 seed: Seed,
1982 lengths_gen: &dyn Fn(Seed) -> I,
1983 xs_gen: &dyn Fn(Seed) -> J,
1984) -> RandomOrderedVecs<T, I, J> {
1985 RandomOrderedVecs {
1986 xs: random_vecs_from_length_iterator(seed, lengths_gen, xs_gen),
1987 }
1988}
1989
1990/// Generates random [`Vec`]s using elements from an iterator, where the elements are in ascending
1991/// order and may repeat.
1992///
1993/// The lengths of the [`Vec`]s are sampled from a geometric distribution with a specified mean $m$,
1994/// equal to `mean_length_numerator / mean_length_denominator`. $m$ must be greater than 0.
1995///
1996/// $$
1997/// P((x\_i)\_{i=0}^{n-1}) = \frac{n!}{\prod\_j m\_j!} P(n) \prod\_{i=0}^{n-1}P(x\_i),
1998/// $$
1999/// where $m\_j$ is the number of times that the $j$th distinct value occurs. The formula assumes
2000/// that the [`Vec`] is valid, \emph{i.e.} its elements are nondecreasing; the probability of an
2001/// invalid [`Vec`] is zero.
2002///
2003/// Sorting gives every multiset a single representation, so two output [`Vec`]s are equal exactly
2004/// when they hold the same elements with the same multiplicities.
2005///
2006/// `xs_gen` must be infinite.
2007///
2008/// # Expected complexity per iteration
2009/// $T(i) = O(m \log m + m T^\prime(i))$
2010///
2011/// $M(i) = O(m M^\prime(i))$
2012///
2013/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
2014/// $M^\prime$ are the time and memory functions of `xs`, and $m$ is `mean_length_numerator /
2015/// mean_length_denominator`.
2016///
2017/// # Panics
2018/// Panics if `mean_length_numerator` or `mean_length_denominator` are zero, or, if after being
2019/// reduced to lowest terms, their sum is greater than or equal to $2^{64}$.
2020///
2021/// # Examples
2022/// ```
2023/// use itertools::Itertools;
2024/// use malachite_base::num::random::random_primitive_ints;
2025/// use malachite_base::random::EXAMPLE_SEED;
2026/// use malachite_base::vecs::random::random_ordered_vecs;
2027///
2028/// let xs = random_ordered_vecs(EXAMPLE_SEED, &random_primitive_ints::<u8>, 4, 1);
2029/// let values = xs.take(20).collect_vec();
2030/// assert_eq!(
2031/// values.iter().map(Vec::as_slice).collect_vec().as_slice(),
2032/// &[
2033/// &[][..],
2034/// &[11, 32, 38, 85, 134, 136, 162, 177, 200, 203, 217, 223, 235, 235],
2035/// &[30, 166, 218, 234],
2036/// &[9, 90, 106, 216],
2037/// &[204],
2038/// &[],
2039/// &[78, 97, 151, 213, 253],
2040/// &[39, 91],
2041/// &[170, 175, 191, 232],
2042/// &[],
2043/// &[2, 22, 35, 198, 217, 233],
2044/// &[],
2045/// &[],
2046/// &[17, 25, 32, 65, 114, 114, 121, 144, 173, 173, 222],
2047/// &[52, 69, 73, 79, 91, 115, 137, 148],
2048/// &[],
2049/// &[112, 153, 178],
2050/// &[],
2051/// &[34, 95, 106, 167, 197],
2052/// &[86, 122, 130, 150, 168, 172, 177, 207, 221]
2053/// ]
2054/// );
2055/// ```
2056#[inline]
2057pub fn random_ordered_vecs<I: Iterator>(
2058 seed: Seed,
2059 xs_gen: &dyn Fn(Seed) -> I,
2060 mean_length_numerator: u64,
2061 mean_length_denominator: u64,
2062) -> RandomOrderedVecs<I::Item, GeometricRandomNaturalValues<u64>, I>
2063where
2064 I::Item: Ord,
2065{
2066 random_ordered_vecs_from_length_iterator(
2067 seed,
2068 &|seed_2| {
2069 geometric_random_unsigneds(seed_2, mean_length_numerator, mean_length_denominator)
2070 },
2071 xs_gen,
2072 )
2073}
2074
2075/// Generates random [`Vec`]s with a minimum length, using elements from an iterator, where the
2076/// elements are in ascending order and may repeat.
2077///
2078/// The lengths of the [`Vec`]s are sampled from a geometric distribution with a specified mean $m$,
2079/// equal to `mean_length_numerator / mean_length_denominator`. $m$ must be greater than
2080/// `min_length`.
2081///
2082/// $$
2083/// P((x\_i)\_{i=0}^{n-1}) = \frac{n!}{\prod\_j m\_j!} P(n) \prod\_{i=0}^{n-1}P(x\_i),
2084/// $$
2085/// where $m\_j$ is the number of times that the $j$th distinct value occurs. The formula assumes
2086/// that the [`Vec`] is valid, \emph{i.e.} its elements are nondecreasing; the probability of an
2087/// invalid [`Vec`] is zero.
2088///
2089/// Sorting gives every multiset a single representation, so two output [`Vec`]s are equal exactly
2090/// when they hold the same elements with the same multiplicities.
2091///
2092/// `xs_gen` must be infinite.
2093///
2094/// # Expected complexity per iteration
2095/// $T(i) = O(m \log m + m T^\prime(i))$
2096///
2097/// $M(i) = O(m M^\prime(i))$
2098///
2099/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
2100/// $M^\prime$ are the time and memory functions of `xs`, and $m$ is `mean_length_numerator /
2101/// mean_length_denominator`.
2102///
2103/// # Panics
2104/// Panics if `mean_length_numerator` or `mean_length_denominator` are zero, if their ratio is less
2105/// than or equal to `min_length`, or if they are too large and manipulating them leads to
2106/// arithmetic overflow.
2107///
2108/// # Examples
2109/// ```
2110/// use itertools::Itertools;
2111/// use malachite_base::num::random::random_primitive_ints;
2112/// use malachite_base::random::EXAMPLE_SEED;
2113/// use malachite_base::vecs::random::random_ordered_vecs_min_length;
2114///
2115/// let xs = random_ordered_vecs_min_length(EXAMPLE_SEED, 2, &random_primitive_ints::<u8>, 6, 1);
2116/// let values = xs.take(20).collect_vec();
2117/// assert_eq!(
2118/// values.iter().map(Vec::as_slice).collect_vec().as_slice(),
2119/// &[
2120/// &[11, 85][..],
2121/// &[30, 32, 38, 134, 136, 162, 166, 177, 200, 203, 217, 218, 223, 234, 235, 235],
2122/// &[9, 90, 106, 151, 204, 216],
2123/// &[39, 78, 91, 97, 213, 253],
2124/// &[170, 175, 191],
2125/// &[232, 233],
2126/// &[2, 17, 22, 35, 114, 198, 217],
2127/// &[32, 65, 114, 173],
2128/// &[25, 121, 144, 148, 173, 222],
2129/// &[79, 115],
2130/// &[52, 69, 73, 91, 112, 137, 153, 178],
2131/// &[34, 95],
2132/// &[106, 167],
2133/// &[86, 101, 115, 122, 130, 150, 168, 172, 177, 197, 207, 218, 221],
2134/// &[9, 48, 52, 74, 109, 123, 159, 201, 247, 250],
2135/// &[133, 235],
2136/// &[40, 68, 97, 104, 196],
2137/// &[190, 216],
2138/// &[7, 43, 43, 112, 157, 216, 217],
2139/// &[11, 24, 29, 55, 65, 84, 89, 103, 135, 206, 211]
2140/// ]
2141/// );
2142/// ```
2143#[inline]
2144pub fn random_ordered_vecs_min_length<I: Iterator>(
2145 seed: Seed,
2146 min_length: u64,
2147 xs_gen: &dyn Fn(Seed) -> I,
2148 mean_length_numerator: u64,
2149 mean_length_denominator: u64,
2150) -> RandomOrderedVecs<I::Item, GeometricRandomNaturalValues<u64>, I>
2151where
2152 I::Item: Ord,
2153{
2154 random_ordered_vecs_from_length_iterator(
2155 seed,
2156 &|seed_2| {
2157 geometric_random_unsigned_inclusive_range(
2158 seed_2,
2159 min_length,
2160 u64::MAX,
2161 mean_length_numerator,
2162 mean_length_denominator,
2163 )
2164 },
2165 xs_gen,
2166 )
2167}
2168
2169/// Generates random [`Vec`]s with lengths in $[a, b)$, using elements from an iterator, where the
2170/// elements are in ascending order and may repeat.
2171///
2172/// $$
2173/// P((x\_i)\_{i=0}^{n-1}) = \frac{n!}{\prod\_j m\_j!} P(n) \prod\_{i=0}^{n-1}P(x\_i),
2174/// $$
2175/// where $m\_j$ is the number of times that the $j$th distinct value occurs. The formula assumes
2176/// that the [`Vec`] is valid, \emph{i.e.} its elements are nondecreasing; the probability of an
2177/// invalid [`Vec`] is zero.
2178///
2179/// Sorting gives every multiset a single representation, so two output [`Vec`]s are equal exactly
2180/// when they hold the same elements with the same multiplicities.
2181///
2182/// `xs_gen` must be infinite.
2183///
2184/// # Expected complexity per iteration
2185/// $T(i) = O(m \log m + m T^\prime(i))$
2186///
2187/// $M(i) = O(m M^\prime(i))$
2188///
2189/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
2190/// $M^\prime$ are the time and memory functions of `xs`, and $m$ is $(a + b) / 2$.
2191///
2192/// # Panics
2193/// Panics if $a \geq b$.
2194///
2195/// # Examples
2196/// ```
2197/// use itertools::Itertools;
2198/// use malachite_base::num::random::random_primitive_ints;
2199/// use malachite_base::random::EXAMPLE_SEED;
2200/// use malachite_base::vecs::random::random_ordered_vecs_length_range;
2201///
2202/// let xs = random_ordered_vecs_length_range(EXAMPLE_SEED, 2, 5, &random_primitive_ints::<u8>);
2203/// let values = xs.take(20).collect_vec();
2204/// assert_eq!(
2205/// values.iter().map(Vec::as_slice).collect_vec().as_slice(),
2206/// &[
2207/// &[11, 85, 136][..],
2208/// &[134, 200, 203, 235],
2209/// &[38, 223, 235],
2210/// &[32, 162, 177, 217],
2211/// &[30, 166, 218, 234],
2212/// &[9, 90, 106],
2213/// &[204, 216],
2214/// &[97, 151, 213],
2215/// &[78, 253],
2216/// &[39, 91, 175, 191],
2217/// &[2, 170, 232, 233],
2218/// &[22, 35, 217],
2219/// &[17, 32, 114, 198],
2220/// &[65, 114, 173],
2221/// &[25, 121, 173, 222],
2222/// &[79, 115, 144, 148],
2223/// &[52, 69, 73, 137],
2224/// &[91, 153],
2225/// &[34, 95, 112, 178],
2226/// &[106, 167]
2227/// ]
2228/// );
2229/// ```
2230#[inline]
2231pub fn random_ordered_vecs_length_range<I: Iterator>(
2232 seed: Seed,
2233 a: u64,
2234 b: u64,
2235 xs_gen: &dyn Fn(Seed) -> I,
2236) -> RandomOrderedVecs<I::Item, RandomUnsignedRange<u64>, I>
2237where
2238 I::Item: Ord,
2239{
2240 random_ordered_vecs_from_length_iterator(
2241 seed,
2242 &|seed_2| random_unsigned_range(seed_2, a, b),
2243 xs_gen,
2244 )
2245}
2246
2247/// Generates random [`Vec`]s with lengths in $[a, b]$, using elements from an iterator, where the
2248/// elements are in ascending order and may repeat.
2249///
2250/// $$
2251/// P((x\_i)\_{i=0}^{n-1}) = \frac{n!}{\prod\_j m\_j!} P(n) \prod\_{i=0}^{n-1}P(x\_i),
2252/// $$
2253/// where $m\_j$ is the number of times that the $j$th distinct value occurs. The formula assumes
2254/// that the [`Vec`] is valid, \emph{i.e.} its elements are nondecreasing; the probability of an
2255/// invalid [`Vec`] is zero.
2256///
2257/// Sorting gives every multiset a single representation, so two output [`Vec`]s are equal exactly
2258/// when they hold the same elements with the same multiplicities.
2259///
2260/// `xs_gen` must be infinite.
2261///
2262/// # Expected complexity per iteration
2263/// $T(i) = O(m \log m + m T^\prime(i))$
2264///
2265/// $M(i) = O(m M^\prime(i))$
2266///
2267/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
2268/// $M^\prime$ are the time and memory functions of `xs`, and $m$ is $(a + b) / 2$.
2269///
2270/// # Panics
2271/// Panics if $a > b$.
2272///
2273/// # Examples
2274/// ```
2275/// use itertools::Itertools;
2276/// use malachite_base::num::random::random_primitive_ints;
2277/// use malachite_base::random::EXAMPLE_SEED;
2278/// use malachite_base::vecs::random::random_ordered_vecs_length_inclusive_range;
2279///
2280/// let xs = random_ordered_vecs_length_inclusive_range(
2281/// EXAMPLE_SEED,
2282/// 2,
2283/// 4,
2284/// &random_primitive_ints::<u8>,
2285/// );
2286/// let values = xs.take(20).collect_vec();
2287/// assert_eq!(
2288/// values.iter().map(Vec::as_slice).collect_vec().as_slice(),
2289/// &[
2290/// &[11, 85, 136][..],
2291/// &[134, 200, 203, 235],
2292/// &[38, 223, 235],
2293/// &[32, 162, 177, 217],
2294/// &[30, 166, 218, 234],
2295/// &[9, 90, 106],
2296/// &[204, 216],
2297/// &[97, 151, 213],
2298/// &[78, 253],
2299/// &[39, 91, 175, 191],
2300/// &[2, 170, 232, 233],
2301/// &[22, 35, 217],
2302/// &[17, 32, 114, 198],
2303/// &[65, 114, 173],
2304/// &[25, 121, 173, 222],
2305/// &[79, 115, 144, 148],
2306/// &[52, 69, 73, 137],
2307/// &[91, 153],
2308/// &[34, 95, 112, 178],
2309/// &[106, 167]
2310/// ]
2311/// );
2312/// ```
2313#[inline]
2314pub fn random_ordered_vecs_length_inclusive_range<I: Iterator>(
2315 seed: Seed,
2316 a: u64,
2317 b: u64,
2318 xs_gen: &dyn Fn(Seed) -> I,
2319) -> RandomOrderedVecs<I::Item, RandomUnsignedInclusiveRange<u64>, I>
2320where
2321 I::Item: Ord,
2322{
2323 random_ordered_vecs_from_length_iterator(
2324 seed,
2325 &|seed_2| random_unsigned_inclusive_range(seed_2, a, b),
2326 xs_gen,
2327 )
2328}
2329
2330#[doc(hidden)]
2331#[derive(Clone, Debug)]
2332pub struct RandomUniqueVecsLength2<I: Iterator>
2333where
2334 I::Item: Eq,
2335{
2336 xs: I,
2337}
2338
2339impl<I: Iterator> Iterator for RandomUniqueVecsLength2<I>
2340where
2341 I::Item: Eq,
2342{
2343 type Item = Vec<I::Item>;
2344
2345 #[inline]
2346 fn next(&mut self) -> Option<Vec<I::Item>> {
2347 let mut out = Vec::with_capacity(2);
2348 loop {
2349 let x = self.xs.next().unwrap();
2350 if out.is_empty() {
2351 out.push(x);
2352 } else if x != out[0] {
2353 out.push(x);
2354 return Some(out);
2355 }
2356 }
2357 }
2358}
2359
2360/// Generates random [`Vec`]s with lengths from an iterator, where the [`Vec`]s have no repeated
2361/// elements.
2362#[derive(Clone, Debug)]
2363pub struct RandomUniqueVecs<T: Eq + Hash, I: Iterator<Item = u64>, J: Iterator<Item = T>> {
2364 lengths: I,
2365 xs: J,
2366}
2367
2368impl<T: Eq + Hash, I: Iterator<Item = u64>, J: Iterator<Item = T>> Iterator
2369 for RandomUniqueVecs<T, I, J>
2370{
2371 type Item = Vec<T>;
2372
2373 fn next(&mut self) -> Option<Vec<T>> {
2374 // We avoid cloning the T values. We first move them into a HashMap, then into a
2375 // Vec<Option<T>>, then into the output Vec<T>.
2376 let len = usize::exact_from(self.lengths.next().unwrap());
2377 let mut xs_to_indices = HashMap::with_capacity(len);
2378 let mut i = 0;
2379 while i < len {
2380 xs_to_indices
2381 .entry(self.xs.next().unwrap())
2382 .or_insert_with(|| {
2383 i += 1;
2384 i - 1
2385 });
2386 }
2387 let mut out = Vec::with_capacity(len);
2388 out.resize_with(len, || None);
2389 for (x, i) in xs_to_indices {
2390 out[i] = Some(x);
2391 }
2392 Some(out.into_iter().map(Option::unwrap).collect())
2393 }
2394}
2395
2396/// Generates random [`Vec`]s using elements from an iterator and with lengths from another
2397/// iterator, where the [`Vec`]s have no repeated elements.
2398///
2399/// The input iterator must generate at least many distinct elements as any number generated by the
2400/// lengths iterator; otherwise, this iterator will hang.
2401///
2402/// `lengths` and `xs` must be infinite.
2403///
2404/// # Expected complexity per iteration
2405/// $T(i) = O(T^{\prime\prime}(i) + \ell T^\prime(i))$
2406///
2407/// $M(i) = O(M^{\prime\prime}(i) + \ell M^\prime(i))$
2408///
2409/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
2410/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`,
2411/// $T^{\prime\prime}$ and $M^{\prime\prime}$ are the time and memory functions of `lengths`, and
2412/// $\ell$ is the $i$th generated length.
2413///
2414/// If `xs` can repeat values, extra draws are needed to reach the required number of distinct
2415/// elements, and an iteration fails to terminate if fewer distinct values are reachable than the
2416/// requested length.
2417///
2418/// # Examples
2419/// ```
2420/// use itertools::Itertools;
2421/// use malachite_base::num::random::random_primitive_ints;
2422/// use malachite_base::random::EXAMPLE_SEED;
2423/// use malachite_base::vecs::random::random_unique_vecs_from_length_iterator;
2424/// use malachite_base::vecs::random_values_from_vec;
2425///
2426/// let xs = random_unique_vecs_from_length_iterator(
2427/// EXAMPLE_SEED,
2428/// &|seed| random_values_from_vec(seed, vec![0, 2, 4]),
2429/// &random_primitive_ints::<u8>,
2430/// );
2431/// let values = xs.take(20).collect_vec();
2432/// assert_eq!(
2433/// values.iter().map(Vec::as_slice).collect_vec().as_slice(),
2434/// &[
2435/// &[85, 11][..],
2436/// &[136, 200, 235, 134],
2437/// &[203, 223],
2438/// &[38, 235, 217, 177],
2439/// &[162, 32, 166, 234],
2440/// &[30, 218],
2441/// &[],
2442/// &[90, 106],
2443/// &[],
2444/// &[9, 216, 204, 151],
2445/// &[213, 97, 253, 78],
2446/// &[91, 39],
2447/// &[191, 175, 170, 232],
2448/// &[233, 2],
2449/// &[35, 22, 217, 198],
2450/// &[114, 17, 32, 173],
2451/// &[114, 65, 121, 222],
2452/// &[],
2453/// &[173, 25, 144, 148],
2454/// &[]
2455/// ]
2456/// );
2457/// ```
2458#[inline]
2459pub fn random_unique_vecs_from_length_iterator<
2460 T: Eq + Hash,
2461 I: Iterator<Item = u64>,
2462 J: Iterator<Item = T>,
2463>(
2464 seed: Seed,
2465 lengths_gen: &dyn Fn(Seed) -> I,
2466 xs_gen: &dyn Fn(Seed) -> J,
2467) -> RandomUniqueVecs<T, I, J> {
2468 RandomUniqueVecs {
2469 lengths: lengths_gen(seed.fork("lengths")),
2470 xs: xs_gen(seed.fork("xs")),
2471 }
2472}
2473
2474/// Generates random [`Vec`]s of a fixed length, where the [`Vec`]s have no repeated elements.
2475///
2476/// This `enum` is created by [`random_unique_vecs_fixed_length`]; see its documentation for more.
2477#[derive(Clone, Debug)]
2478pub enum RandomUniqueVecsFixedLength<I: Iterator>
2479where
2480 I::Item: Eq + Hash,
2481{
2482 Zero,
2483 One(I),
2484 Two(RandomUniqueVecsLength2<I>),
2485 GreaterThan2(RandomUniqueVecs<I::Item, Repeat<u64>, I>),
2486}
2487
2488impl<I: Iterator> Iterator for RandomUniqueVecsFixedLength<I>
2489where
2490 I::Item: Eq + Hash,
2491{
2492 type Item = Vec<I::Item>;
2493
2494 #[inline]
2495 fn next(&mut self) -> Option<Vec<I::Item>> {
2496 match self {
2497 Self::Zero => Some(vec![]),
2498 Self::One(xs) => xs.next().map(|x| vec![x]),
2499 Self::Two(xs) => xs.next(),
2500 Self::GreaterThan2(xs) => xs.next(),
2501 }
2502 }
2503}
2504
2505/// Randomly generates [`Vec`]s of a given length, where the [`Vec`]s have no repeated elements.
2506///
2507/// The input iterator must generate at least `len` distinct elements; otherwise, this iterator will
2508/// hang.
2509///
2510/// If `len` is 0, the output consists of the empty list, repeated.
2511///
2512/// `xs` must be infinite.
2513///
2514/// # Expected complexity per iteration
2515/// $T(i) = O(\ell T^\prime(i))$
2516///
2517/// $M(i) = O(\ell M^\prime(i))$
2518///
2519/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
2520/// $M^\prime$ are the time and memory functions of `xs`, and $\ell$ is `len`.
2521///
2522/// If `xs` can repeat values, extra draws are needed to reach the required number of distinct
2523/// elements, and an iteration fails to terminate if fewer distinct values are reachable than the
2524/// requested length.
2525///
2526/// # Expected complexity per iteration
2527/// $T(i) = O(m T^\prime(i))$
2528///
2529/// $M(i) = O(m M^\prime(i))$
2530///
2531/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
2532/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`, and $m$ is
2533/// `mean_length_numerator / mean_length_denominator`.
2534///
2535/// If `xs` can repeat values, extra draws are needed to reach the required number of distinct
2536/// elements, and an iteration fails to terminate if fewer distinct values are reachable than the
2537/// requested length.
2538///
2539/// # Examples
2540/// ```
2541/// use itertools::Itertools;
2542/// use malachite_base::num::random::random_unsigned_inclusive_range;
2543/// use malachite_base::random::EXAMPLE_SEED;
2544/// use malachite_base::vecs::random::random_unique_vecs_fixed_length;
2545///
2546/// let xss = random_unique_vecs_fixed_length(
2547/// 2,
2548/// random_unsigned_inclusive_range::<u32>(EXAMPLE_SEED, 1, 100),
2549/// )
2550/// .take(10)
2551/// .collect_vec();
2552/// assert_eq!(
2553/// xss.iter().map(Vec::as_slice).collect_vec().as_slice(),
2554/// &[
2555/// &[95, 24],
2556/// &[99, 71],
2557/// &[93, 53],
2558/// &[85, 34],
2559/// &[48, 2],
2560/// &[55, 11],
2561/// &[48, 18],
2562/// &[90, 93],
2563/// &[67, 93],
2564/// &[93, 95]
2565/// ]
2566/// );
2567/// ```
2568#[inline]
2569pub fn random_unique_vecs_fixed_length<I: Iterator>(
2570 len: u64,
2571 xs: I,
2572) -> RandomUniqueVecsFixedLength<I>
2573where
2574 I::Item: Eq + Hash,
2575{
2576 match len {
2577 0 => RandomUniqueVecsFixedLength::Zero,
2578 1 => RandomUniqueVecsFixedLength::One(xs),
2579 2 => RandomUniqueVecsFixedLength::Two(RandomUniqueVecsLength2 { xs }),
2580 len => RandomUniqueVecsFixedLength::GreaterThan2(RandomUniqueVecs {
2581 lengths: repeat(len),
2582 xs,
2583 }),
2584 }
2585}
2586
2587/// Generates random [`Vec`]s using elements from an iterator, where the [`Vec`]s have no repeated
2588/// elements.
2589///
2590/// The lengths of the [`Vec`]s are sampled from a geometric distribution with a specified mean $m$,
2591/// equal to `mean_length_numerator / mean_length_denominator`. $m$ must be greater than 0.
2592///
2593/// Strictly speaking, the input iterator must generate infinitely many distinct elements. In
2594/// practice it only needs to generate $k$ distinct elements, where $k$ is the largest length
2595/// actually sampled from the geometric distribution. For example, if `mean_length_numerator /
2596/// mean_length_denominator` is significantly lower than 256, then it's ok to use
2597/// `random_unsigneds::<u8>`.
2598///
2599/// `xs_gen` must be infinite.
2600///
2601/// # Expected complexity per iteration
2602/// $T(i) = O(m T^\prime(i))$
2603///
2604/// $M(i) = O(m M^\prime(i))$
2605///
2606/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
2607/// $M^\prime$ are the time and memory functions of `xs`, and $m$ is `mean_length_numerator /
2608/// mean_length_denominator`.
2609///
2610/// # Panics
2611/// Panics if `mean_length_numerator` or `mean_length_denominator` are zero, or, if after being
2612/// reduced to lowest terms, their sum is greater than or equal to $2^{64}$.
2613///
2614/// # Examples
2615/// ```
2616/// use itertools::Itertools;
2617/// use malachite_base::num::random::random_primitive_ints;
2618/// use malachite_base::random::EXAMPLE_SEED;
2619/// use malachite_base::vecs::random::random_unique_vecs;
2620///
2621/// let xs = random_unique_vecs(EXAMPLE_SEED, &random_primitive_ints::<u8>, 4, 1);
2622/// let values = xs.take(20).collect_vec();
2623/// assert_eq!(
2624/// values.iter().map(Vec::as_slice).collect_vec().as_slice(),
2625/// &[
2626/// &[][..],
2627/// &[85, 11, 136, 200, 235, 134, 203, 223, 38, 217, 177, 162, 32, 166],
2628/// &[234, 30, 218, 90],
2629/// &[106, 9, 216, 204],
2630/// &[151],
2631/// &[],
2632/// &[213, 97, 253, 78, 91],
2633/// &[39, 191],
2634/// &[175, 170, 232, 233],
2635/// &[],
2636/// &[2, 35, 22, 217, 198, 114],
2637/// &[],
2638/// &[],
2639/// &[17, 32, 173, 114, 65, 121, 222, 25, 144, 148, 79],
2640/// &[115, 52, 73, 69, 137, 91, 153, 178],
2641/// &[],
2642/// &[112, 34, 95],
2643/// &[],
2644/// &[106, 167, 197, 130, 168],
2645/// &[122, 207, 172, 177, 86, 150, 221, 218, 101]
2646/// ]
2647/// );
2648/// ```
2649#[inline]
2650pub fn random_unique_vecs<I: Iterator>(
2651 seed: Seed,
2652 xs_gen: &dyn Fn(Seed) -> I,
2653 mean_length_numerator: u64,
2654 mean_length_denominator: u64,
2655) -> RandomUniqueVecs<I::Item, GeometricRandomNaturalValues<u64>, I>
2656where
2657 I::Item: Eq + Hash,
2658{
2659 random_unique_vecs_from_length_iterator(
2660 seed,
2661 &|seed_2| {
2662 geometric_random_unsigneds(seed_2, mean_length_numerator, mean_length_denominator)
2663 },
2664 xs_gen,
2665 )
2666}
2667
2668/// Generates random [`Vec`]s with a minimum length, using elements from an iterator, where the
2669/// [`Vec`]s have no repeated elements.
2670///
2671/// Strictly speaking, the input iterator must generate infinitely many distinct elements. In
2672/// practice it only needs to generate $k$ distinct elements, where $k$ is the largest length
2673/// actually sampled from the geometric distribution. For example, if `mean_length_numerator /
2674/// mean_length_denominator` is significantly lower than 256, then it's ok to use
2675/// `random_unsigneds::<u8>`.
2676///
2677/// `xs_gen` must be infinite.
2678///
2679/// # Expected complexity per iteration
2680/// $T(i) = O(m T^\prime(i))$
2681///
2682/// $M(i) = O(m M^\prime(i))$
2683///
2684/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
2685/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`, and $m$ is
2686/// `mean_length_numerator / mean_length_denominator`.
2687///
2688/// If `xs` can repeat values, extra draws are needed to reach the required number of distinct
2689/// elements, and an iteration fails to terminate if fewer distinct values are reachable than the
2690/// requested length.
2691///
2692/// # Panics
2693/// Panics if `mean_length_numerator` or `mean_length_denominator` are zero, if their ratio is less
2694/// than or equal to `min_length`, or if they are too large and manipulating them leads to
2695/// arithmetic overflow.
2696///
2697/// # Examples
2698/// ```
2699/// use itertools::Itertools;
2700/// use malachite_base::num::random::random_primitive_ints;
2701/// use malachite_base::random::EXAMPLE_SEED;
2702/// use malachite_base::vecs::random::random_unique_vecs_min_length;
2703///
2704/// let xs = random_unique_vecs_min_length(EXAMPLE_SEED, 2, &random_primitive_ints::<u8>, 6, 1);
2705/// let values = xs.take(20).collect_vec();
2706/// assert_eq!(
2707/// values.iter().map(Vec::as_slice).collect_vec().as_slice(),
2708/// &[
2709/// &[85, 11][..],
2710/// &[136, 200, 235, 134, 203, 223, 38, 217, 177, 162, 32, 166, 234, 30, 218, 90],
2711/// &[106, 9, 216, 204, 151, 213],
2712/// &[97, 253, 78, 91, 39, 191],
2713/// &[175, 170, 232],
2714/// &[233, 2],
2715/// &[35, 22, 217, 198, 114, 17, 32],
2716/// &[173, 114, 65, 121],
2717/// &[222, 173, 25, 144, 148, 79],
2718/// &[115, 52],
2719/// &[73, 69, 137, 91, 153, 178, 112, 34],
2720/// &[95, 106],
2721/// &[167, 197],
2722/// &[130, 168, 122, 207, 172, 177, 86, 150, 221, 218, 101, 115, 74],
2723/// &[9, 123, 109, 52, 201, 159, 247, 250, 48, 133],
2724/// &[235, 196],
2725/// &[40, 97, 104, 68, 190],
2726/// &[216, 7],
2727/// &[216, 157, 43, 112, 217, 24, 11],
2728/// &[103, 211, 84, 135, 55, 29, 206, 89, 65, 191, 51]
2729/// ]
2730/// );
2731/// ```
2732#[inline]
2733pub fn random_unique_vecs_min_length<I: Iterator>(
2734 seed: Seed,
2735 min_length: u64,
2736 xs_gen: &dyn Fn(Seed) -> I,
2737 mean_length_numerator: u64,
2738 mean_length_denominator: u64,
2739) -> RandomUniqueVecs<I::Item, GeometricRandomNaturalValues<u64>, I>
2740where
2741 I::Item: Eq + Hash,
2742{
2743 random_unique_vecs_from_length_iterator(
2744 seed,
2745 &|seed_2| {
2746 geometric_random_unsigned_inclusive_range(
2747 seed_2,
2748 min_length,
2749 u64::MAX,
2750 mean_length_numerator,
2751 mean_length_denominator,
2752 )
2753 },
2754 xs_gen,
2755 )
2756}
2757
2758/// Generates random [`Vec`]s with lengths in $[a, b)$, using elements from an iterator, where the
2759/// [`Vec`]s have no repeated elements.
2760///
2761/// The lengths of the [`Vec`]s are sampled from a uniform distribution on $[a, b)$. $a$ must be
2762/// less than $b$.
2763///
2764/// The input iterator must generate at least $b$ distinct elements.
2765///
2766/// `xs_gen` must be infinite.
2767///
2768/// # Expected complexity per iteration
2769/// $T(i) = O(b T^\prime(i))$
2770///
2771/// $M(i) = O(b M^\prime(i))$
2772///
2773/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
2774/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`, and $b$ is
2775/// `b`.
2776///
2777/// If `xs` can repeat values, extra draws are needed to reach the required number of distinct
2778/// elements, and an iteration fails to terminate if fewer distinct values are reachable than the
2779/// requested length.
2780///
2781/// # Panics
2782/// Panics if $a \geq b$.
2783///
2784/// # Examples
2785/// ```
2786/// use itertools::Itertools;
2787/// use malachite_base::num::random::random_primitive_ints;
2788/// use malachite_base::random::EXAMPLE_SEED;
2789/// use malachite_base::vecs::random::random_unique_vecs_length_range;
2790///
2791/// let xs = random_unique_vecs_length_range(EXAMPLE_SEED, 2, 5, &random_primitive_ints::<u8>);
2792/// let values = xs.take(20).collect_vec();
2793/// assert_eq!(
2794/// values.iter().map(Vec::as_slice).collect_vec().as_slice(),
2795/// &[
2796/// &[85, 11, 136][..],
2797/// &[200, 235, 134, 203],
2798/// &[223, 38, 235],
2799/// &[217, 177, 162, 32],
2800/// &[166, 234, 30, 218],
2801/// &[90, 106, 9],
2802/// &[216, 204],
2803/// &[151, 213, 97],
2804/// &[253, 78],
2805/// &[91, 39, 191, 175],
2806/// &[170, 232, 233, 2],
2807/// &[35, 22, 217],
2808/// &[198, 114, 17, 32],
2809/// &[173, 114, 65],
2810/// &[121, 222, 173, 25],
2811/// &[144, 148, 79, 115],
2812/// &[52, 73, 69, 137],
2813/// &[91, 153],
2814/// &[178, 112, 34, 95],
2815/// &[106, 167]
2816/// ]
2817/// );
2818/// ```
2819#[inline]
2820pub fn random_unique_vecs_length_range<I: Iterator>(
2821 seed: Seed,
2822 a: u64,
2823 b: u64,
2824 xs_gen: &dyn Fn(Seed) -> I,
2825) -> RandomUniqueVecs<I::Item, RandomUnsignedRange<u64>, I>
2826where
2827 I::Item: Eq + Hash,
2828{
2829 random_unique_vecs_from_length_iterator(
2830 seed,
2831 &|seed_2| random_unsigned_range(seed_2, a, b),
2832 xs_gen,
2833 )
2834}
2835
2836/// Generates random [`Vec`]s with lengths in $[a, b]$, using elements from an iterator, where the
2837/// [`Vec`]s have no repeated elements.
2838///
2839/// The lengths of the [`Vec`]s are sampled from a uniform distribution on $[a, b]$. $a$ must be
2840/// less than or equal to $b$.
2841///
2842/// The input iterator must generate at least $b$ distinct elements.
2843///
2844/// `xs_gen` must be infinite.
2845///
2846/// # Expected complexity per iteration
2847/// $T(i) = O(b T^\prime(i))$
2848///
2849/// $M(i) = O(b M^\prime(i))$
2850///
2851/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
2852/// $M^\prime$ are the time and memory functions of the iterators produced by `xs_gen`, and $b$ is
2853/// `b`.
2854///
2855/// If `xs` can repeat values, extra draws are needed to reach the required number of distinct
2856/// elements, and an iteration fails to terminate if fewer distinct values are reachable than the
2857/// requested length.
2858///
2859/// # Panics
2860/// Panics if $a > b$.
2861///
2862/// # Examples
2863/// ```
2864/// use itertools::Itertools;
2865/// use malachite_base::num::random::random_primitive_ints;
2866/// use malachite_base::random::EXAMPLE_SEED;
2867/// use malachite_base::vecs::random::random_unique_vecs_length_inclusive_range;
2868///
2869/// let xs =
2870/// random_unique_vecs_length_inclusive_range(EXAMPLE_SEED, 2, 4, &random_primitive_ints::<u8>);
2871/// let values = xs.take(20).collect_vec();
2872/// assert_eq!(
2873/// values.iter().map(Vec::as_slice).collect_vec().as_slice(),
2874/// &[
2875/// &[85, 11, 136][..],
2876/// &[200, 235, 134, 203],
2877/// &[223, 38, 235],
2878/// &[217, 177, 162, 32],
2879/// &[166, 234, 30, 218],
2880/// &[90, 106, 9],
2881/// &[216, 204],
2882/// &[151, 213, 97],
2883/// &[253, 78],
2884/// &[91, 39, 191, 175],
2885/// &[170, 232, 233, 2],
2886/// &[35, 22, 217],
2887/// &[198, 114, 17, 32],
2888/// &[173, 114, 65],
2889/// &[121, 222, 173, 25],
2890/// &[144, 148, 79, 115],
2891/// &[52, 73, 69, 137],
2892/// &[91, 153],
2893/// &[178, 112, 34, 95],
2894/// &[106, 167]
2895/// ]
2896/// );
2897/// ```
2898#[inline]
2899pub fn random_unique_vecs_length_inclusive_range<I: Iterator>(
2900 seed: Seed,
2901 a: u64,
2902 b: u64,
2903 xs_gen: &dyn Fn(Seed) -> I,
2904) -> RandomUniqueVecs<I::Item, RandomUnsignedInclusiveRange<u64>, I>
2905where
2906 I::Item: Eq + Hash,
2907{
2908 random_unique_vecs_from_length_iterator(
2909 seed,
2910 &|seed_2| random_unsigned_inclusive_range(seed_2, a, b),
2911 xs_gen,
2912 )
2913}