Skip to content

TupleCombinations: size_hint and count #763

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 67 additions & 1 deletion src/adaptors/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub use self::map::{map_into, map_ok, MapInto, MapOk};
#[cfg(feature = "use_alloc")]
pub use self::multi_product::*;

use crate::size_hint;
use crate::size_hint::{self, SizeHint};
use std::fmt;
use std::iter::{FromIterator, Fuse, FusedIterator};
use std::marker::PhantomData;
Expand Down Expand Up @@ -626,6 +626,14 @@ where
fn next(&mut self) -> Option<Self::Item> {
self.iter.next()
}

fn size_hint(&self) -> SizeHint {
self.iter.size_hint()
}

fn count(self) -> usize {
self.iter.count()
}
}

impl<I, T> FusedIterator for TupleCombinations<I, T>
Expand All @@ -652,6 +660,14 @@ impl<I: Iterator> Iterator for Tuple1Combination<I> {
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|x| (x,))
}

fn size_hint(&self) -> SizeHint {
self.iter.size_hint()
}

fn count(self) -> usize {
self.iter.count()
}
}

impl<I: Iterator> HasCombination<I> for (I::Item,) {
Expand Down Expand Up @@ -701,6 +717,20 @@ macro_rules! impl_tuple_combination {
})
}
}

fn size_hint(&self) -> SizeHint {
const K: usize = 1 + count_ident!($($X,)*);
let (mut n_min, mut n_max) = self.iter.size_hint();
n_min = checked_binomial(n_min, K).unwrap_or(usize::MAX);
n_max = n_max.and_then(|n| checked_binomial(n, K));
size_hint::add(self.c.size_hint(), (n_min, n_max))
}

fn count(self) -> usize {
const K: usize = 1 + count_ident!($($X,)*);
let n = self.iter.count();
checked_binomial(n, K).unwrap() + self.c.count()
}
}

impl<I, A> HasCombination<I> for (A, $(ignore_ident!($X, A)),*)
Expand Down Expand Up @@ -736,6 +766,42 @@ impl_tuple_combination!(Tuple10Combination Tuple9Combination; a b c d e f g h i)
impl_tuple_combination!(Tuple11Combination Tuple10Combination; a b c d e f g h i j);
impl_tuple_combination!(Tuple12Combination Tuple11Combination; a b c d e f g h i j k);

// https://en.wikipedia.org/wiki/Binomial_coefficient#In_programming_languages
pub(crate) fn checked_binomial(mut n: usize, mut k: usize) -> Option<usize> {
if n < k {
return Some(0);
}
// `factorial(n) / factorial(n - k) / factorial(k)` but trying to avoid it overflows:
k = (n - k).min(k); // symmetry
let mut c = 1;
for i in 1..=k {
c = (c / i)
.checked_mul(n)?
.checked_add((c % i).checked_mul(n)? / i)?;
n -= 1;
}
Some(c)
}

#[test]
fn test_checked_binomial() {
// With the first row: [1, 0, 0, ...] and the first column full of 1s, we check
// row by row the recurrence relation of binomials (which is an equivalent definition).
// For n >= 1 and k >= 1 we have:
// binomial(n, k) == binomial(n - 1, k - 1) + binomial(n - 1, k)
const LIMIT: usize = 500;
let mut row = vec![Some(0); LIMIT + 1];
row[0] = Some(1);
for n in 0..=LIMIT {
for k in 0..=LIMIT {
assert_eq!(row[k], checked_binomial(n, k));
}
row = std::iter::once(Some(1))
.chain((1..=LIMIT).map(|k| row[k - 1]?.checked_add(row[k]?)))
.collect();
}
}

/// An iterator adapter to filter values within a nested `Result::Ok`.
///
/// See [`.filter_ok()`](crate::Itertools::filter_ok) for more information.
Expand Down
38 changes: 2 additions & 36 deletions src/combinations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ use std::iter::FusedIterator;
use super::lazy_buffer::LazyBuffer;
use alloc::vec::Vec;

use crate::adaptors::checked_binomial;

/// An iterator to iterate through all the `k`-length combinations in an iterator.
///
/// See [`.combinations()`](crate::Itertools::combinations) for more information.
Expand Down Expand Up @@ -160,42 +162,6 @@ where
{
}

// https://en.wikipedia.org/wiki/Binomial_coefficient#In_programming_languages
pub(crate) fn checked_binomial(mut n: usize, mut k: usize) -> Option<usize> {
if n < k {
return Some(0);
}
// `factorial(n) / factorial(n - k) / factorial(k)` but trying to avoid it overflows:
k = (n - k).min(k); // symmetry
let mut c = 1;
for i in 1..=k {
c = (c / i)
.checked_mul(n)?
.checked_add((c % i).checked_mul(n)? / i)?;
n -= 1;
}
Some(c)
}

#[test]
fn test_checked_binomial() {
// With the first row: [1, 0, 0, ...] and the first column full of 1s, we check
// row by row the recurrence relation of binomials (which is an equivalent definition).
// For n >= 1 and k >= 1 we have:
// binomial(n, k) == binomial(n - 1, k - 1) + binomial(n - 1, k)
const LIMIT: usize = 500;
let mut row = vec![Some(0); LIMIT + 1];
row[0] = Some(1);
for n in 0..=LIMIT {
for k in 0..=LIMIT {
assert_eq!(row[k], checked_binomial(n, k));
}
row = std::iter::once(Some(1))
.chain((1..=LIMIT).map(|k| row[k - 1]?.checked_add(row[k]?)))
.collect();
}
}

/// For a given size `n`, return the count of remaining combinations or None if it would overflow.
fn remaining_for(n: usize, first: bool, indices: &[usize]) -> Option<usize> {
let k = indices.len();
Expand Down
2 changes: 1 addition & 1 deletion src/combinations_with_replacement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::fmt;
use std::iter::FusedIterator;

use super::lazy_buffer::LazyBuffer;
use crate::combinations::checked_binomial;
use crate::adaptors::checked_binomial;

/// An iterator to iterate through all the `n`-length combinations in an iterator, with replacement.
///
Expand Down
5 changes: 5 additions & 0 deletions src/impl_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,8 @@ macro_rules! clone_fields {
macro_rules! ignore_ident{
($id:ident, $($t:tt)*) => {$($t)*};
}

macro_rules! count_ident {
() => {0};
($i0:ident, $($i:ident,)*) => {1 + count_ident!($($i,)*)};
}
3 changes: 2 additions & 1 deletion src/powerset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ use std::fmt;
use std::iter::FusedIterator;
use std::usize;

use super::combinations::{checked_binomial, combinations, Combinations};
use super::combinations::{combinations, Combinations};
use crate::adaptors::checked_binomial;
use crate::size_hint::{self, SizeHint};

/// An iterator to iterate through the powerset of the elements from an iterator.
Expand Down
4 changes: 0 additions & 4 deletions src/tuple_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -297,10 +297,6 @@ pub trait TupleCollect: Sized {
fn left_shift_push(&mut self, item: Self::Item);
}

macro_rules! count_ident{
() => {0};
($i0:ident, $($i:ident,)*) => {1 + count_ident!($($i,)*)};
}
macro_rules! rev_for_each_ident{
($m:ident, ) => {};
($m:ident, $i0:ident, $($i:ident,)*) => {
Expand Down
27 changes: 25 additions & 2 deletions tests/quick.rs
Original file line number Diff line number Diff line change
Expand Up @@ -901,8 +901,31 @@ quickcheck! {
}

quickcheck! {
fn size_combinations(it: Iter<i16>) -> bool {
correct_size_hint(it.tuple_combinations::<(_, _)>())
fn size_combinations(a: Iter<i16>) -> bool {
let it = a.clone().tuple_combinations::<(_, _)>();
correct_size_hint(it.clone()) && it.count() == binomial(a.count(), 2)
}

fn exact_size_combinations_1(a: Vec<u8>) -> bool {
let it = a.iter().tuple_combinations::<(_,)>();
exact_size_for_this(it.clone()) && it.count() == binomial(a.len(), 1)
}
fn exact_size_combinations_2(a: Vec<u8>) -> bool {
let it = a.iter().tuple_combinations::<(_, _)>();
exact_size_for_this(it.clone()) && it.count() == binomial(a.len(), 2)
}
fn exact_size_combinations_3(mut a: Vec<u8>) -> bool {
a.truncate(15);
let it = a.iter().tuple_combinations::<(_, _, _)>();
exact_size_for_this(it.clone()) && it.count() == binomial(a.len(), 3)
}
}

fn binomial(n: usize, k: usize) -> usize {
if k > n {
0
} else {
(n - k + 1..=n).product::<usize>() / (1..=k).product::<usize>()
}
}

Expand Down
6 changes: 6 additions & 0 deletions tests/specializations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,12 @@ where
}

quickcheck! {
fn tuple_combinations(v: Vec<u8>) -> () {
let mut v = v;
v.truncate(10);
test_specializations(&v.iter().tuple_combinations::<(_, _, _)>());
}

fn intersperse(v: Vec<u8>) -> () {
test_specializations(&v.into_iter().intersperse(0));
}
Expand Down