Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
def combos(items, k, s = 0, combo = [])
return [combo] if k == 0
(s .. items.size - k).flat_map do |i|
combos(items, k - 1, i + 1, combo + [items[i]])
end
end
combos([:a, :b, :c, :d, :e, :f], 3).each do |combo|
p combo
end
use std::iter;
fn combos<T>(items: &[T], k: usize) -> impl Iterator<Item = Vec<&T>> {
combo_helper(items, Vec::new(), k)
}
fn combo_helper<'a, T>(
items: &'a [T],
combo: Vec<&'a T>,
k: usize,
) -> Box<dyn Iterator<Item = Vec<&'a T>> + 'a> {
if k == 0 {
return Box::new(iter::once(combo));
}
let iter = (0..=items.len() - k).flat_map(move |i| {
let mut cc = combo.clone();
cc.push(&items[i]);
combo_helper(&items[i + 1..], cc, k - 1)
});
Box::new(iter)
}
fn main() {
for combo in combos(&['a', 'b', 'c', 'd', 'e', 'f'], 3) {
println!("{:?}", combo);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment