usecrate::it::cloned; usecrate::it::free::put_back_n; usecrate::it::free::rciter; usecrate::it::iproduct; usecrate::it::izip; usecrate::it::multipeek; usecrate::it::multizip; usecrate::it::peek_nth; usecrate::it::repeat_n; usecrate::it::ExactlyOneError; usecrate::it::FoldWhile; usecrate::it::Itertools; use itertools as it; use quickcheck as qc; use rand::{
distributions::{Distribution, Standard},
rngs::StdRng,
Rng, SeedableRng,
}; use rand::{seq::SliceRandom, thread_rng}; use std::{cmp::min, fmt::Debug, marker::PhantomData};
#[test] fn product3() { let prod = iproduct!(0..3, 0..2, 0..2);
assert_eq!(prod.size_hint(), (12, Some(12))); let v = prod.collect_vec(); for i in0..3 { for j in0..2 { for k in0..2 {
assert!((i, j, k) == v[(i * 2 * 2 + j * 2 + k) as usize]);
}
}
} for (_, _, _, _) in iproduct!(0..3, 0..2, 0..2, 0..3) { /* test compiles */ }
}
#[test] fn interleave_shortest() { let v0: Vec<i32> = vec![0, 2, 4]; let v1: Vec<i32> = vec![1, 3, 5, 7]; let it = v0.into_iter().interleave_shortest(v1);
assert_eq!(it.size_hint(), (6, Some(6)));
assert_eq!(it.collect_vec(), vec![0, 1, 2, 3, 4, 5]);
let v0: Vec<i32> = vec![0, 2, 4, 6, 8]; let v1: Vec<i32> = vec![1, 3, 5]; let it = v0.into_iter().interleave_shortest(v1);
assert_eq!(it.size_hint(), (7, Some(7)));
assert_eq!(it.collect_vec(), vec![0, 1, 2, 3, 4, 5, 6]);
let i0 = ::std::iter::repeat(0); let v1: Vec<_> = vec![1, 3, 5]; let it = i0.interleave_shortest(v1);
assert_eq!(it.size_hint(), (7, Some(7)));
let v0: Vec<_> = vec![0, 2, 4]; let i1 = ::std::iter::repeat(1); let it = v0.into_iter().interleave_shortest(i1);
assert_eq!(it.size_hint(), (6, Some(6)));
}
let v = (0..5).sorted_by(|&a, &b| a.cmp(&b).reverse());
it::assert_equal(v, vec![4, 3, 2, 1, 0]);
}
#[cfg(not(miri))]
qc::quickcheck! { fn k_smallest_range(n: i64, m: u16, k: u16) -> () { // u16 is used to constrain k and m to 0..2¹⁶, // otherwise the test could use too much memory. let (k, m) = (k as usize, m as u64);
letmut v: Vec<_> = (n..n.saturating_add(m as _)).collect(); // Generate a random permutation of n..n+m
v.shuffle(&mut thread_rng());
// Construct the right answers for the top and bottom elements letmut sorted = v.clone();
sorted.sort(); // how many elements are we checking let num_elements = min(k, m as _);
// Compute the top and bottom k in various combinations let sorted_smallest = sorted[..num_elements].iter().cloned(); let smallest = v.iter().cloned().k_smallest(k); let smallest_by = v.iter().cloned().k_smallest_by(k, Ord::cmp); let smallest_by_key = v.iter().cloned().k_smallest_by_key(k, |&x| x);
let sorted_largest = sorted[sorted.len() - num_elements..].iter().rev().cloned(); let largest = v.iter().cloned().k_largest(k); let largest_by = v.iter().cloned().k_largest_by(k, Ord::cmp); let largest_by_key = v.iter().cloned().k_largest_by_key(k, |&x| x);
// Check the variations produce the same answers and that they're right
it::assert_equal(smallest, sorted_smallest.clone());
it::assert_equal(smallest_by, sorted_smallest.clone());
it::assert_equal(smallest_by_key, sorted_smallest);
fn k_smallest_relaxed_range(n: i64, m: u16, k: u16) -> () { // u16 is used to constrain k and m to 0..2¹⁶, // otherwise the test could use too much memory. let (k, m) = (k as usize, m as u64);
letmut v: Vec<_> = (n..n.saturating_add(m as _)).collect(); // Generate a random permutation of n..n+m
v.shuffle(&mut thread_rng());
// Construct the right answers for the top and bottom elements letmut sorted = v.clone();
sorted.sort(); // how many elements are we checking let num_elements = min(k, m as _);
// Compute the top and bottom k in various combinations let sorted_smallest = sorted[..num_elements].iter().cloned(); let smallest = v.iter().cloned().k_smallest_relaxed(k); let smallest_by = v.iter().cloned().k_smallest_relaxed_by(k, Ord::cmp); let smallest_by_key = v.iter().cloned().k_smallest_relaxed_by_key(k, |&x| x);
let sorted_largest = sorted[sorted.len() - num_elements..].iter().rev().cloned(); let largest = v.iter().cloned().k_largest_relaxed(k); let largest_by = v.iter().cloned().k_largest_relaxed_by(k, Ord::cmp); let largest_by_key = v.iter().cloned().k_largest_relaxed_by_key(k, |&x| x);
// Check the variations produce the same answers and that they're right
it::assert_equal(smallest, sorted_smallest.clone());
it::assert_equal(smallest_by, sorted_smallest.clone());
it::assert_equal(smallest_by_key, sorted_smallest);
// Check that taking the k smallest is the same as // sorting then taking the k first elements fn k_smallest_sort<I>(i: I, k: u16) where
I: Iterator + Clone,
I::Item: Ord + Debug,
{ let j = i.clone(); let i1 = i.clone(); let j1 = i.clone(); let k = k as usize;
it::assert_equal(i.k_smallest(k), j.sorted().take(k));
it::assert_equal(i1.k_smallest_relaxed(k), j1.sorted().take(k));
}
// Similar to `k_smallest_sort` but for our custom heap implementation. fn k_smallest_by_sort<I>(i: I, k: u16) where
I: Iterator + Clone,
I::Item: Ord + Debug,
{ let j = i.clone(); let i1 = i.clone(); let j1 = i.clone(); let k = k as usize;
it::assert_equal(i.k_smallest_by(k, Ord::cmp), j.sorted().take(k));
it::assert_equal(i1.k_smallest_relaxed_by(k, Ord::cmp), j1.sorted().take(k));
}
let v = (0..5).sorted_by_key(|&x| -x);
it::assert_equal(v, vec![4, 3, 2, 1, 0]);
}
#[test] fn sorted_by_cached_key() { // Track calls to key function letmut ncalls = 0;
let sorted = [3, 4, 1, 2].iter().cloned().sorted_by_cached_key(|&x| {
ncalls += 1;
x.to_string()
});
it::assert_equal(sorted, vec![1, 2, 3, 4]); // Check key function called once per element
assert_eq!(ncalls, 4);
letmut ncalls = 0;
let sorted = (0..5).sorted_by_cached_key(|&x| {
ncalls += 1;
-x
});
it::assert_equal(sorted, vec![4, 3, 2, 1, 0]); // Check key function called once per element
assert_eq!(ncalls, 5);
}
let v: Vec<usize> = vec![0, 1, 2]; let r = v.into_iter().pad_using(5, |n| n);
it::assert_equal(r, vec![0, 1, 2, 3, 4]);
let v: Vec<usize> = vec![0, 1, 2]; let r = v.into_iter().pad_using(1, |_| panic!());
it::assert_equal(r, vec![0, 1, 2]);
}
#[test] fn chunk_by() { for (ch1, sub) in &"AABBCCC".chars().chunk_by(|&x| x) { for ch2 in sub {
assert_eq!(ch1, ch2);
}
}
for (ch1, sub) in &"AAABBBCCCCDDDD".chars().chunk_by(|&x| x) { for ch2 in sub {
assert_eq!(ch1, ch2); if ch1 == 'C' { break;
}
}
}
let toupper = |ch: &char| ch.to_uppercase().next().unwrap();
// try all possible orderings for indices in permutohedron::Heap::new(&mut [0, 1, 2, 3]) { let chunks = "AaaBbbccCcDDDD".chars().chunk_by(&toupper); letmut subs = chunks.into_iter().collect_vec();
for &idx in &indices[..] { let (key, text) = match idx { 0 => ('A', "Aaa".chars()), 1 => ('B', "Bbb".chars()), 2 => ('C', "ccCc".chars()), 3 => ('D', "DDDD".chars()),
_ => unreachable!(),
};
assert_eq!(key, subs[idx].0);
it::assert_equal(&mut subs[idx].1, text);
}
}
let sd = subs.pop().unwrap(); let sc = subs.pop().unwrap(); let sb = subs.pop().unwrap(); let sa = subs.pop().unwrap(); for (a, b, c, d) in multizip((sa, sb, sc, sd)) {
assert_eq!(a, 'A');
assert_eq!(b, 'B');
assert_eq!(c, 'C');
assert_eq!(d, 'D');
}
// check that the key closure is called exactly n times
{ letmut ntimes = 0; let text = "AABCCC"; for (_, sub) in &text.chars().chunk_by(|&x| {
ntimes += 1;
x
}) { for _ in sub {}
}
assert_eq!(ntimes, text.len());
}
{ letmut ntimes = 0; let text = "AABCCC"; for _ in &text.chars().chunk_by(|&x| {
ntimes += 1;
x
}) {}
assert_eq!(ntimes, text.len());
}
{ let text = "ABCCCDEEFGHIJJKK"; let gr = text.chars().chunk_by(|&x| x);
it::assert_equal(gr.into_iter().flat_map(|(_, sub)| sub), text.chars());
}
}
#[test] fn chunk_by_lazy_2() { let data = [0, 1]; let chunks = data.iter().chunk_by(|k| *k); let gs = chunks.into_iter().collect_vec();
it::assert_equal(data.iter(), gs.into_iter().flat_map(|(_k, g)| g));
let data = [0, 1, 1, 0, 0]; let chunks = data.iter().chunk_by(|k| *k); letmut gs = chunks.into_iter().collect_vec();
gs[1..].reverse();
it::assert_equal(&[0, 0, 0, 1, 1], gs.into_iter().flat_map(|(_, g)| g));
let grouper = data.iter().chunk_by(|k| *k); letmut chunks = Vec::new(); for (k, chunk) in &grouper { if *k == 1 {
chunks.push(chunk);
}
}
it::assert_equal(&mut chunks[0], &[1, 1]);
let data = [0, 0, 0, 1, 1, 0, 0, 2, 2, 3, 3]; let grouper = data.iter().chunk_by(|k| *k); letmut chunks = Vec::new(); for (i, (_, chunk)) in grouper.into_iter().enumerate() { if i < 2 {
chunks.push(chunk);
} elseif i < 4 { for _ in chunk {}
} else {
chunks.push(chunk);
}
}
it::assert_equal(&mut chunks[0], &[0, 0, 0]);
it::assert_equal(&mut chunks[1], &[1, 1]);
it::assert_equal(&mut chunks[2], &[3, 3]);
let data = [0, 0, 0, 1, 1, 0, 0, 2, 2, 3, 3]; letmut i = 0; let grouper = data.iter().chunk_by(move |_| { let k = i / 3;
i += 1;
k
}); for (i, chunk) in &grouper { match i { 0 => it::assert_equal(chunk, &[0, 0, 0]), 1 => it::assert_equal(chunk, &[1, 1, 0]), 2 => it::assert_equal(chunk, &[0, 2, 2]), 3 => it::assert_equal(chunk, &[3, 3]),
_ => unreachable!(),
}
}
}
#[test] fn chunk_by_lazy_3() { // test consuming each chunk on the lap after it was produced let data = [0, 0, 0, 1, 1, 0, 0, 1, 1, 2, 2]; let grouper = data.iter().chunk_by(|elt| *elt); letmut last = None; for (key, chunk) in &grouper { iflet Some(gr) = last.take() { for elt in gr {
assert!(elt != key && i32::abs(elt - key) == 1);
}
}
last = Some(chunk);
}
}
#[test] fn chunks() { let data = [0, 0, 0, 1, 1, 0, 0, 2, 2, 3, 3]; let grouper = data.iter().chunks(3); for (i, chunk) in grouper.into_iter().enumerate() { match i { 0 => it::assert_equal(chunk, &[0, 0, 0]), 1 => it::assert_equal(chunk, &[1, 1, 0]), 2 => it::assert_equal(chunk, &[0, 2, 2]), 3 => it::assert_equal(chunk, &[3, 3]),
_ => unreachable!(),
}
}
}
fn binomial(n: usize, k: usize) -> usize { if k > n { 0
} else {
(n - k + 1..=n).product::<usize>() / (1..=k).product::<usize>()
}
}
#[test] fn combinations_range_count() { for n in0..=7 { for k in0..=7 { let len = binomial(n, k); letmut it = (0..n).combinations(k);
assert_eq!(len, it.clone().count());
assert_eq!(len, it.size_hint().0);
assert_eq!(Some(len), it.size_hint().1); for count in (0..len).rev() { let elem = it.next();
assert!(elem.is_some());
assert_eq!(count, it.clone().count());
assert_eq!(count, it.size_hint().0);
assert_eq!(Some(count), it.size_hint().1);
} let should_be_none = it.next();
assert!(should_be_none.is_none());
}
}
}
#[test] fn combinations_inexact_size_hints() { for k in0..=7 { letmut numbers = (0..18).filter(|i| i % 2 == 0); // 9 elements letmut it = numbers.clone().combinations(k); let real_n = numbers.clone().count(); let len = binomial(real_n, k);
assert_eq!(len, it.clone().count());
letmut nb_loaded = 0; let sh = numbers.size_hint();
assert_eq!(binomial(sh.0 + nb_loaded, k), it.size_hint().0);
assert_eq!(sh.1.map(|n| binomial(n + nb_loaded, k)), it.size_hint().1);
for next_count in1..=len { let elem = it.next();
assert!(elem.is_some());
assert_eq!(len - next_count, it.clone().count()); if next_count == 1 { // The very first time, the lazy buffer is prefilled.
nb_loaded = numbers.by_ref().take(k).count();
} else { // Then it loads one item each time until exhausted. let nb = numbers.next(); if nb.is_some() {
nb_loaded += 1;
}
} let sh = numbers.size_hint(); if next_count > real_n - k + 1 {
assert_eq!(0, sh.0);
assert_eq!(Some(0), sh.1);
assert_eq!(real_n, nb_loaded); // Once it's fully loaded, size hints of `it` are exacts.
}
assert_eq!(binomial(sh.0 + nb_loaded, k) - next_count, it.size_hint().0);
assert_eq!(
sh.1.map(|n| binomial(n + nb_loaded, k) - next_count),
it.size_hint().1
);
} let should_be_none = it.next();
assert!(should_be_none.is_none());
}
}
#[test] fn permutations_range_count() { for n in0..=4 { for k in0..=4 { let len = if k <= n { (n - k + 1..=n).product() } else { 0 }; letmut it = (0..n).permutations(k);
assert_eq!(len, it.clone().count());
assert_eq!(len, it.size_hint().0);
assert_eq!(Some(len), it.size_hint().1); for count in (0..len).rev() { let elem = it.next();
assert!(elem.is_some());
assert_eq!(count, it.clone().count());
assert_eq!(count, it.size_hint().0);
assert_eq!(Some(count), it.size_hint().1);
} let should_be_none = it.next();
assert!(should_be_none.is_none());
}
}
}
#[test] #[cfg(not(miri))] fn combinations_with_replacement() { // Pool smaller than n
it::assert_equal((0..1).combinations_with_replacement(2), vec![vec![0, 0]]); // Pool larger than n
it::assert_equal(
(0..3).combinations_with_replacement(2),
vec![
vec![0, 0],
vec![0, 1],
vec![0, 2],
vec![1, 1],
vec![1, 2],
vec![2, 2],
],
); // Zero size
it::assert_equal((0..3).combinations_with_replacement(0), vec![vec![]]); // Zero size on empty pool
it::assert_equal((0..0).combinations_with_replacement(0), vec![vec![]]); // Empty pool
it::assert_equal(
(0..0).combinations_with_replacement(2),
<Vec<Vec<_>>>::new(),
);
}
#[test] fn combinations_with_replacement_range_count() { for n in0..=4 { for k in0..=4 { let len = binomial(usize::saturating_sub(n + k, 1), k); letmut it = (0..n).combinations_with_replacement(k);
assert_eq!(len, it.clone().count());
assert_eq!(len, it.size_hint().0);
assert_eq!(Some(len), it.size_hint().1); for count in (0..len).rev() { let elem = it.next();
assert!(elem.is_some());
assert_eq!(count, it.clone().count());
assert_eq!(count, it.size_hint().0);
assert_eq!(Some(count), it.size_hint().1);
} let should_be_none = it.next();
assert!(should_be_none.is_none());
}
}
}
for n in0..=4 { letmut it = (0..n).powerset(); let len = 2_usize.pow(n);
assert_eq!(len, it.clone().count());
assert_eq!(len, it.size_hint().0);
assert_eq!(Some(len), it.size_hint().1); for count in (0..len).rev() { let elem = it.next();
assert!(elem.is_some());
assert_eq!(count, it.clone().count());
assert_eq!(count, it.size_hint().0);
assert_eq!(Some(count), it.size_hint().1);
} let should_be_none = it.next();
assert!(should_be_none.is_none());
}
}
#[test] fn diff_mismatch() { let a = [1, 2, 3, 4]; let b = vec![1.0, 5.0, 3.0, 4.0]; let b_map = b.into_iter().map(|f| f as i32); let diff = it::diff_with(a.iter(), b_map, |a, b| *a == b);
#[test] fn diff_longer() { let a = [1, 2, 3, 4]; let b = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]; let b_map = b.into_iter().map(|f| f as i32); let diff = it::diff_with(a.iter(), b_map, |a, b| *a == b);
#[test] fn diff_shorter() { let a = [1, 2, 3, 4]; let b = vec![1.0, 2.0]; let b_map = b.into_iter().map(|f| f as i32); let diff = it::diff_with(a.iter(), b_map, |a, b| *a == b);
#[test] fn extrema_set() { use std::cmp::Ordering;
// A peculiar type: Equality compares both tuple items, but ordering only the // first item. Used to distinguish equal elements. #[derive(Clone, Debug, PartialEq, Eq)] struct Val(u32, u32);
impl PartialOrd<Self> for Val { fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Val { fn cmp(&self, other: &Self) -> Ordering { self.0.cmp(&other.0)
}
}
let max_set = data.iter().max_set();
assert_eq!(max_set, vec![&Val(2, 0), &Val(>2, 1)]);
let max_set_by_key = data.iter().max_set_by_key(|v| v.1);
assert_eq!(max_set_by_key, vec![&Val(0, 2)]);
let max_set_by = data.iter().max_set_by(|x, y| x.1.cmp(&y.1));
assert_eq!(max_set_by, vec![&Val(0, 2)]);
}
#[test] fn minmax() { usecrate::it::MinMaxResult; use std::cmp::Ordering;
// A peculiar type: Equality compares both tuple items, but ordering only the // first item. This is so we can check the stability property easily. #[derive(Clone, Debug, PartialEq, Eq)] struct Val(u32, u32);
impl PartialOrd<Self> for Val { fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Val { fn cmp(&self, other: &Self) -> Ordering { self.0.cmp(&other.0)
}
}
#[test] fn tree_reduce() { let x = [ "", "0", "0 1 x", "0 1 x 2 x", "0 1 x 2 3 x x", "0 1 x 2 3 x x 4 x", "0 1 x 2 3 x x 4 5 x x", "0 1 x 2 3 x x 4 5 x 6 x x", "0 1 x 2 3 x x 4 5 x 6 7 x x x", "0 1 x 2 3 x x 4 5 x 6 7 x x x 8 x", "0 1 x 2 3 x x 4 5 x 6 7 x x x 8 9 x x", "0 1 x 2 3 x x 4 5 x 6 7 x x x 8 9 x 10 x x", "0 1 x 2 3 x x 4 5 x 6 7 x x x 8 9 x 10 11 x x x", "0 1 x 2 3 x x 4 5 x 6 7 x x x 8 9 x 10 11 x x 12 x x", "0 1 x 2 3 x x 4 5 x 6 7 x x x 8 9 x 10 11 x x 12 13 x x x", "0 1 x 2 3 x x 4 5 x 6 7 x x x 8 9 x 10 11 x x 12 13 x 14 x x x", "0 1 x 2 3 x x 4 5 x 6 7 x x x 8 9 x 10 11 x x 12 13 x 14 15 x x x x",
]; for (i, &s) in x.iter().enumerate() { let expected = if s.is_empty() {
None
} else {
Some(s.to_string())
}; let num_strings = (0..i).map(|x| x.to_string()); let actual = num_strings.tree_reduce(|a, b| format!("{} {} x", a, b));
assert_eq!(actual, expected);
}
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.