rewrite broken combinations iterator and cleanup of utils
This commit is contained in:
parent
6a58f37ad7
commit
2e5fb4cf38
@ -6,6 +6,7 @@ where
|
|||||||
k: usize,
|
k: usize,
|
||||||
size: usize,
|
size: usize,
|
||||||
pool: Vec<I::Item>,
|
pool: Vec<I::Item>,
|
||||||
|
first: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<I, T> Combinations<I, T>
|
impl<I, T> Combinations<I, T>
|
||||||
@ -15,11 +16,20 @@ where
|
|||||||
pub fn new(iter: I, k: usize) -> Self {
|
pub fn new(iter: I, k: usize) -> Self {
|
||||||
let pool: Vec<I::Item> = iter.collect();
|
let pool: Vec<I::Item> = iter.collect();
|
||||||
|
|
||||||
|
if k > pool.len() {
|
||||||
|
panic!(
|
||||||
|
"No combinations possible for len {} and k {}",
|
||||||
|
pool.len(),
|
||||||
|
k
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
indices: (0..k).collect(),
|
indices: (0..k).collect(),
|
||||||
k,
|
k,
|
||||||
size: pool.len(),
|
size: pool.len(),
|
||||||
pool,
|
pool,
|
||||||
|
first: true,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -32,30 +42,26 @@ where
|
|||||||
type Item = Vec<T>;
|
type Item = Vec<T>;
|
||||||
|
|
||||||
fn next(&mut self) -> Option<Self::Item> {
|
fn next(&mut self) -> Option<Self::Item> {
|
||||||
let mut out = Vec::with_capacity(self.size);
|
if self.first {
|
||||||
let mut indices = Vec::with_capacity(self.k);
|
self.first = false;
|
||||||
let mut incremented = false;
|
} else {
|
||||||
|
let mut i = self.k - 1;
|
||||||
|
|
||||||
for i in &self.indices {
|
while self.indices[i] == i + self.size - self.k {
|
||||||
out.push(self.pool[*i]);
|
if i > 0 {
|
||||||
}
|
i -= 1;
|
||||||
|
} else {
|
||||||
self.indices.reverse();
|
|
||||||
let mut iter = self.indices.iter().enumerate();
|
|
||||||
while let Some((count, idx)) = iter.next() {
|
|
||||||
if incremented || *idx == self.size - (count + 1) {
|
|
||||||
indices.push(*idx);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
indices.push(idx + 1);
|
|
||||||
incremented = true;
|
|
||||||
}
|
|
||||||
if !incremented {
|
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
indices.reverse();
|
}
|
||||||
self.indices = indices;
|
|
||||||
Some(out)
|
self.indices[i] += 1;
|
||||||
|
for j in i + 1..self.k {
|
||||||
|
self.indices[j] = self.indices[j - 1] + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(self.indices.iter().map(|i| self.pool[*i]).collect())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -66,8 +72,3 @@ pub trait CombinationsIterator<T>: Iterator<Item = T> + Sized {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<I, T> CombinationsIterator<T> for I where I: Iterator<Item = T> {}
|
impl<I, T> CombinationsIterator<T> for I where I: Iterator<Item = T> {}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_iter() {
|
|
||||||
println!("{:?}", [1, 2, 3].iter().combinations(2).collect::<Vec<_>>());
|
|
||||||
}
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user