Skip to content

Instantly share code, notes, and snippets.

@jcoglan
Created August 20, 2020 23:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcoglan/2b32c5f5b660ffa86a801e38532a4d5a to your computer and use it in GitHub Desktop.
Save jcoglan/2b32c5f5b660ffa86a801e38532a4d5a to your computer and use it in GitHub Desktop.
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