Ben Chuanlong Du's Blog

It is never too late to learn.

Generate Combinations Using Itertools in Rust

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

In [ ]:
:timing
:sccache 1

Tips and Traps

IterTools.combinations returns an iterator adaptor that iterates over the k-length combinations of the elements from an iterator. The iterator element type is Vec<Self::Item>. This means that

  1. Element of the original iterator need to be clonable.
  2. For copy/clone-expensive types, it is better to use collect elements into a vector and generate indexes instead.
In [4]:
:dep itertools = "0.10.0"
In [5]:
use itertools::Itertools;
In [10]:
let it = (1..5).combinations(3);
it
Out[10]:
Combinations { indices: [0, 1, 2], pool: LazyBuffer { it: 4..5, done: false, buffer: [1, 2, 3] }, first: true }
In [11]:
let v = it.collect::<Vec<_>>();
v
Out[11]:
[[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]
In [12]:
v
Out[12]:
[[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]

Note: Combinations does not take into account the equality of the iterated values!

In [11]:
{
    let it = vec![1, 2, 2].into_iter().combinations(2);
    it.collect::<Vec<Vec<_>>>()
}
Out[11]:
[[1, 2], [1, 2], [2, 2]]
In [7]:
(1..5).rev().combinations(3).collect::<Vec<Vec<_>>>()
Out[7]:
[[4, 3, 2], [4, 3, 1], [4, 2, 1], [3, 2, 1]]
In [ ]:

Comments