Skip to content
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

Array combinations #546

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
50 changes: 50 additions & 0 deletions benches/tuple_combinations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,51 @@ fn tuple_comb_c4(c: &mut Criterion) {
});
}


fn array_comb_c1(c: &mut Criterion) {
c.bench_function("array comb c1", move |b| {
b.iter(|| {
for [i] in (0..N1).array_combinations() {
black_box(i);
}
})
});
}


fn array_comb_c2(c: &mut Criterion) {
c.bench_function("array comb c2", move |b| {
b.iter(|| {
for [i, j] in (0..N2).array_combinations() {
black_box(i + j);
}
})
});
}


fn array_comb_c3(c: &mut Criterion) {
c.bench_function("array comb c3", move |b| {
b.iter(|| {
for [i, j, k] in (0..N3).array_combinations() {
black_box(i + j + k);
}
})
});
}


fn array_comb_c4(c: &mut Criterion) {
c.bench_function("array comb c4", move |b| {
b.iter(|| {
for [i, j, k, l] in (0..N4).array_combinations() {
black_box(i + j + k + l);
}
})
});
}


criterion_group!(
benches,
tuple_comb_for1,
Expand All @@ -109,5 +154,10 @@ criterion_group!(
tuple_comb_c2,
tuple_comb_c3,
tuple_comb_c4,
array_comb_c1,
array_comb_c2,
array_comb_c3,
array_comb_c4,
);

criterion_main!(benches);
66 changes: 66 additions & 0 deletions src/adaptors/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -812,6 +812,72 @@ 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);

#[derive(Debug, Clone)]
pub struct ArrayCombinations<T, const R: usize> {
slice: Vec<T>,
indices: [usize; R],
}

impl<T, const R: usize> ArrayCombinations<T, R> {
pub fn new(slice: Vec<T>) -> Self {
debug_assert!(slice.len() >= R);

let mut indices = [0; R];
for i in 1..R {
indices[i] = i;
}

Self {
slice,
indices,
}
}
}

impl<T: Clone, const R: usize> Iterator for ArrayCombinations<T, R> {
type Item = [T; R];

fn next(&mut self) -> Option<Self::Item> {
if self.indices[R-1] == self.slice.len() {
return None;
}

// SAFETY: uninitialized data is never read
let output = unsafe {
let mut output: [T; R] = std::mem::uninitialized();
for i in 0..R {
output[i] = self.slice[self.indices[i]].clone();
}
output
};
conradludgate marked this conversation as resolved.
Show resolved Hide resolved

// // The below uses currently unstable rust. Once they are stable
// // we can replace the deprecated uninitialized

// let mut output = std::mem::MaybeUninit::uninit_array::<R>();
// for i in 0..R {
// // SAFETY: only writing so no UB
// unsafe {
// *output[i].as_mut_ptr() = self.slice[self.indicies[i]].clone();
// }
// }
// // SAFETY: initialised above
// let output = unsafe { std::mem::MaybeUninit::array_assume_init(output) };

let mut i = R-1;
while i > 0 && self.indices[i] + R == self.slice.len() + i {
i -= 1;
}

self.indices[i] += 1;
for j in i+1..R {
self.indices[j] = self.indices[j-1] + 1;
}

Some(output)
}
}

/// An iterator adapter to filter values within a nested `Result::Ok`.
///
/// See [`.filter_ok()`](crate::Itertools::filter_ok) for more information.
Expand Down
8 changes: 8 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ pub mod structs {
WhileSome,
Coalesce,
TupleCombinations,
ArrayCombinations,
Positions,
Update,
};
Expand Down Expand Up @@ -1449,6 +1450,13 @@ pub trait Itertools : Iterator {
adaptors::tuple_combinations(self)
}

fn array_combinations<const R: usize>(self) -> ArrayCombinations<Self::Item, R>
where Self: Sized,
Self::Item: Clone + std::fmt::Debug,
{
ArrayCombinations::new(self.collect())
conradludgate marked this conversation as resolved.
Show resolved Hide resolved
}

/// Return an iterator adaptor that iterates over the `k`-length combinations of
/// the elements from an iterator.
///
Expand Down
20 changes: 20 additions & 0 deletions tests/quick.rs
Original file line number Diff line number Diff line change
Expand Up @@ -895,6 +895,26 @@ quickcheck! {
}
}

quickcheck! {
fn equal_combinations_array(it: Iter<i16>) -> bool {
let values = it.clone().collect_vec();
if values.len() < 2 {
return true;
}

let mut cmb = it.array_combinations();
for i in 0..values.len() {
for j in i+1..values.len() {
let pair = [values[i], values[j]];
if pair != cmb.next().unwrap() {
return false;
}
}
}
cmb.next() == None
}
}

quickcheck! {
fn size_pad_tail(it: Iter<i8>, pad: u8) -> bool {
correct_size_hint(it.clone().pad_using(pad as usize, |_| 0)) &&
Expand Down