1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
// Copyright © 2026 Mikhail Hogrefe
//
// This file is part of Malachite.
//
// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
use crate;
use crateParity;
use crateZero;
use crateSeed;
use crate;
use VecDeque;
use ;
use Vec;
use Display;
use Hash;
use HashSet;
use Itertools;
/// Generates all the nonzero values of a provided iterator.
///
/// This `struct` is created by [`nonzero_values`]; see its documentation for more.
where
Item: + Zero;
/// Returns an iterator that generates all the nonzero values of a provided iterator.
///
/// `nonzero_values(xs)` generates the same values as `xs.filter(|x| x != I::Item::ZERO)`, but its
/// type is easier to work with.
///
/// This iterator will hang if given an iterator that produces an infinite suffix of zeros.
///
/// The output length is the number of nonzero values produced by `xs`.
///
/// # Worst-case complexity per iteration
/// $T(i) = O(z T^\prime(i))$
///
/// $M(i) = O(M^\prime(i))$
///
/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
/// $M^\prime$ are the time and memory functions of `xs`, and $z$ is the number of consecutive zeros
/// that must be skipped to reach the next nonzero value.
///
/// # Examples
/// ```
/// use itertools::Itertools;
/// use malachite_base::iterators::nonzero_values;
///
/// assert_eq!(
/// nonzero_values([-3i8, -2, -1, 0, 1, 2, 3].iter().cloned()).collect_vec(),
/// &[-3, -2, -1, 1, 2, 3]
/// )
/// ```
pub const
/// Returns whether all of the values generated by an iterator are equal.
///
/// `is_constant(xs)` is equivalent to `xs.unique().count() == 1` for finite nonempty iterators, but
/// is more efficient, doesn't require [`Clone`] or [`Hash`] implementations, and doesn't hang if
/// provided an infinite non-constant iterator.
///
/// This function will hang if given an infinite constant iterator.
///
/// # Examples
/// ```
/// use malachite_base::iterators::is_constant;
///
/// assert_eq!(is_constant([1; 4].iter()), true);
/// assert_eq!(is_constant([1, 2, 3, 4].iter()), false);
/// assert_eq!(is_constant(0..), false);
/// ```
/// Returns whether an iterator returns at least some number of values.
///
/// `count_is_at_least(xs, n)` is equivalent to `xs.count() >= n` for finite iterators, but doesn't
/// hang if provided an infinite iterator.
///
/// # Examples
/// ```
/// use malachite_base::iterators::count_is_at_least;
///
/// assert_eq!(count_is_at_least([1, 2, 3, 4].iter(), 3), true);
/// assert_eq!(count_is_at_least([1, 2, 3, 4].iter(), 4), true);
/// assert_eq!(count_is_at_least([1, 2, 3, 4].iter(), 5), false);
/// assert_eq!(count_is_at_least(0.., 5), true);
/// ```
/// Returns whether an iterator returns at most some number of values.
///
/// `count_is_at_most(xs, n)` is equivalent to `xs.count() <= n` for finite iterators, but doesn't
/// hang if provided an infinite iterator.
///
/// # Examples
/// ```
/// use malachite_base::iterators::count_is_at_most;
///
/// assert_eq!(count_is_at_most([1, 2, 3, 4].iter(), 3), false);
/// assert_eq!(count_is_at_most([1, 2, 3, 4].iter(), 4), true);
/// assert_eq!(count_is_at_most([1, 2, 3, 4].iter(), 5), true);
/// assert_eq!(count_is_at_most(0.., 5), false);
/// ```
/// Returns whether an iterator never returns the same value twice.
///
/// `is_unique(xs)` is equivalent to `xs.unique().count() <= 1` for finite iterators, but is more
/// efficient and doesn't hang if provided a non-unique infinite iterator.
///
/// This iterator will hang if given an infinite unique iterator.
///
/// # Examples
/// ```
/// use malachite_base::iterators::is_unique;
///
/// let empty: [u32; 0] = [];
/// assert_eq!(is_unique(empty.iter()), true);
/// assert_eq!(is_unique([1, 2, 3, 4].iter()), true);
/// assert_eq!(is_unique([1, 2, 3, 1].iter()), false);
/// assert_eq!(is_unique((0..).map(|i| i / 2)), false);
/// ```
/// Returns the first and last elements of an iterator, or `None` if it is empty.
///
/// The iterator's elements must be cloneable, since if the iterator consists of a single element
/// `x`, the result will be `(x, x)`.
///
/// This iterator will hang if given an infinite iterator.
///
/// # Examples
/// ```
/// use malachite_base::iterators::first_and_last;
///
/// let empty: [u32; 0] = [];
/// assert_eq!(first_and_last(&mut empty.iter()), None);
/// assert_eq!(first_and_last(&mut [1].iter().cloned()), Some((1, 1)));
/// assert_eq!(first_and_last(&mut [1, 2, 3].iter().cloned()), Some((1, 3)));
/// ```
/// Folds an iterator by merging its elements in a balanced binary tree rather than linearly.
///
/// A linear fold combines an ever-growing accumulator with each new element, which is wasteful when
/// the cost of `merge` grows more than linearly in the sizes of its arguments, as it does for
/// bignum multiplication. This function instead maintains a stack of intermediate results, where
/// the $k$th entry from the top is the merge of about $2^k$ consecutive elements, so merges tend to
/// combine values of comparable size. The stack never holds more than $\lceil \log_2 n \rceil + 1$
/// entries.
///
/// The `merge` function must be associative, but need not be commutative: `merge(a, b)` always
/// receives a block of consecutive elements `a` immediately followed by the block `b`, and must
/// store the combination of the two in `a`. `None` is returned if the iterator is empty.
///
/// If an element for which `is_absorbing` returns true is encountered, it is returned immediately,
/// and the rest of the iterator is not consumed. This short-circuits, for example, a product that
/// encounters a zero.
///
/// The pairing is oblivious to the actual sizes of the values, which is optimal when the elements
/// have comparable sizes and within a factor of $O(\log n)$ of optimal in general. When one element
/// dominates all the others combined (say, one million-bit factor among thousands of word-sized
/// ones), a size-aware merge order can win that factor back; measured against a smallest-first
/// heap, this function loses at most about $2.5\times$ on such distributions while winning on
/// uniform ones. Callers with known-pathological size distributions can sort by size before
/// folding.
///
/// # Worst-case complexity
/// $T(n) = O(n\mu)$
///
/// $M(n) = O(m\log n)$
///
/// where $T$ is time, $M$ is additional memory, $n$ is `xs.count()`, $\mu$ is the worst-case time
/// of `merge`, and $m$ is the largest size of any intermediate value.
///
/// # Examples
/// ```
/// use malachite_base::iterators::balanced_fold;
///
/// // The merges form a balanced tree, preserving the order of the elements.
/// assert_eq!(
/// balanced_fold(
/// ["a", "b", "c", "d", "e"].into_iter().map(String::from),
/// |_| false,
/// |a, b| *a = format!("({a}{b})"),
/// )
/// .unwrap(),
/// "(((ab)(cd))e)"
/// );
///
/// // An absorbing element short-circuits.
/// assert_eq!(
/// balanced_fold([5u32, 6, 0, 7].into_iter(), |&x| x == 0, |a, b| *a *= b),
/// Some(0)
/// );
///
/// assert_eq!(
/// balanced_fold([5u32, 6, 7].into_iter(), |_| false, |a, b| *a *= b),
/// Some(210)
/// );
/// assert_eq!(
/// balanced_fold(std::iter::empty::<u32>(), |_| false, |a, b| *a *= b),
/// None
/// );
/// ```
/// Groups elements of an iterator into intervals of adjacent elements that match a predicate. The
/// endpoints of each interval are returned.
///
/// The intervals are inclusive.
///
/// This iterator will hang if given an infinite iterator.
///
/// # Examples
/// ```
/// use malachite_base::iterators::matching_intervals_in_iterator;
///
/// let xs = &[1, 2, 10, 11, 12, 7, 8, 16, 5];
/// assert_eq!(
/// matching_intervals_in_iterator(xs.iter().cloned(), |&x| x >= 10).as_slice(),
/// &[(10, 12), (16, 16)]
/// );
/// assert_eq!(
/// matching_intervals_in_iterator(xs.iter().cloned(), |&x| x < 10).as_slice(),
/// &[(1, 2), (7, 8), (5, 5)]
/// );
/// ```
/// An iterator that randomly produces another iterator's values, or produces a special value.
///
/// This `struct` is created by [`with_special_value`]; see its documentation for more.
/// An iterator that randomly produces another iterator's values, or produces a special value.
///
/// Let $n_p$ be `p_numerator`, $d_p$ be `p_denominator`, and let $p=n_p/d_p$.
///
/// Every time a value is to be generated, the iterator returns the special value with probability
/// $p$, or else returns a value from the inner iterator.
///
/// If $p > 0$, the output length is infinite. Otherwise, it is the same as the length of `xs`.
///
/// # Panics
/// Panics if `p_denominator` is 0 or `p_numerator` is greater than `p_denominator`.
///
/// # Examples
/// ```
/// use malachite_base::iterators::{prefix_to_string, with_special_value};
/// use malachite_base::num::random::random_primitive_ints;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
/// prefix_to_string(
/// with_special_value(EXAMPLE_SEED, -1i16, 1, 2, &random_primitive_ints::<i16>),
/// 20
/// ),
/// "[-1, -1, -1, 2901, -1, -14200, -1, -1, -1, -30997, -8245, -5338, -1, -1, -20007, -1, -1, \
/// -1, -1, -1, ...]"
/// );
/// ```
/// An iterator that randomly produces another iterator's values, or samples from a [`Vec`] of
/// special values.
///
/// This `struct` is created by [`with_special_values`]; see its documentation for more.
/// An iterator that randomly produces another iterator's values, or produces a random special value
/// from a [`Vec`].
///
/// Let $n_p$ be `p_numerator`, $d_p$ be `p_denominator`, and let $p=n_p/d_p$.
///
/// Every time a value is to be generated, the iterator uniformly samples the special values [`Vec`]
/// with probability $p$, or else returns a value from the inner iterator.
///
/// If $p > 0$, the output length is infinite. Otherwise, it is the same as the length of `xs`.
///
/// # Worst-case complexity per iteration
/// Constant time and additional memory.
///
/// # Panics
/// Panics if `special_values` is empty, `p_denominator` is 0, or if `p_numerator` is greater than
/// `p_denominator`.
///
/// # Examples
/// ```
/// use malachite_base::iterators::{prefix_to_string, with_special_values};
/// use malachite_base::num::random::random_primitive_ints;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
/// prefix_to_string(
/// with_special_values(
/// EXAMPLE_SEED,
/// vec![1, 2, 3],
/// 1,
/// 2,
/// &random_primitive_ints::<i16>
/// ),
/// 20,
/// ),
/// "[3, 1, 3, 2901, 1, -14200, 2, 3, 1, -30997, -8245, -5338, 1, 1, -20007, 3, 1, 1, 1, 1, \
/// ...]"
/// );
/// ```
/// Generates sliding windows of elements from an iterator.
///
/// This `struct` is created by [`iter_windows`]; see its documentation for more.
/// Returns windows of $n$ adjacent elements of an iterator, advancing the window by 1 in each
/// iteration. The values are cloned each time a new window is generated.
///
/// The output length is $n - k + 1$, where $n$ is `xs.count()` and $k$ is `window_size`.
///
/// # Worst-case complexity per iteration
/// $T(i) = O(\ell + T^\prime(i))$
///
/// $M(i) = O(\ell + M^\prime(i))$
///
/// where $T$ is time, $M$ is additional memory, $i$ is the iteration number, $T^\prime$ and
/// $M^\prime$ are the time and memory functions of `xs`, and $\ell$ is `window_size`.
///
/// # Panics
/// Panics if `window_size` is 0.
///
/// # Examples
/// ```
/// use itertools::Itertools;
/// use malachite_base::iterators::iter_windows;
///
/// let xs = 0..=5;
/// let windows = iter_windows(3, xs)
/// .map(|ws| ws.iter().cloned().collect_vec())
/// .collect_vec();
/// assert_eq!(
/// windows.iter().map(Vec::as_slice).collect_vec().as_slice(),
/// &[&[0, 1, 2], &[1, 2, 3], &[2, 3, 4], &[3, 4, 5]]
/// );
/// ```
/// Converts a prefix of an iterator to a string.
///
/// Suppose the iterator generates $(a, b, c, d)$. If `max_len` is 3, this function will return the
/// string `"[a, b, c, ...]"`. If `max_len` is 4 or more, this function will return `[a, b, c, d]`.
///
/// This function will attempt to advance the iterator `max_len + 1` times. The extra time is used
/// determine whether the output string should contain an ellipsis.
///
/// # Panics
/// Panics if `max_len` is 0.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
///
/// assert_eq!(prefix_to_string(0..10, 3), "[0, 1, 2, ...]");
/// assert_eq!(prefix_to_string(0..4, 5), "[0, 1, 2, 3]");
/// ```
/// An iterator that generates the Thue-Morse sequence. See [`thue_morse_sequence`] for more
/// information.
;
/// Returns an iterator that generates the Thue-Morse sequence.
///
/// The output length is infinite.
///
/// # Worst-case complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::thue_morse_sequence;
///
/// let s: String = thue_morse_sequence()
/// .take(100)
/// .map(|b| if b { '1' } else { '0' })
/// .collect();
/// assert_eq!(
/// s,
/// "01101001100101101001011001101001100101100110100101101001100101101001011001101001011010011\
/// 00101100110"
/// )
/// ```
pub const
/// Contains [`BitDistributor`](bit_distributor::BitDistributor), which helps generate tuples
/// exhaustively.
/// Functions that compare adjacent iterator elements.
/// Contains [`IteratorCache`](iterator_cache::IteratorCache), which remembers values produced by an
/// iterator.