Skip to content

Instantly share code, notes, and snippets.

@jcoglan
Created August 20, 2020 23:33
Show Gist options
  • Select an option

  • Save jcoglan/2b32c5f5b660ffa86a801e38532a4d5a to your computer and use it in GitHub Desktop.

Select an option

Save jcoglan/2b32c5f5b660ffa86a801e38532a4d5a to your computer and use it in GitHub Desktop.

Revisions

  1. jcoglan created this gist Aug 20, 2020.
    11 changes: 11 additions & 0 deletions combinations.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,11 @@
    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
    29 changes: 29 additions & 0 deletions combinations.rs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    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);
    }
    }