pub trait Combinations {
type Item;
// Required methods
fn combinations(&self, k: usize) -> CombinationIter<'_, Self::Item> ⓘ;
fn combinations_range(
&self,
range: impl RangeBounds<usize>,
) -> CombinationRangeIter<'_, Self::Item> ⓘ;
}Expand description
Extension trait providing combination methods on slices.
use combinations::Combinations;
let items = [1, 2, 3, 4];
// All pairs
let pairs: Vec<Vec<&i32>> = items.combinations(2).collect();
assert_eq!(pairs.len(), 6);
// Works on Vec too
let v = vec!["a", "b", "c"];
for combo in v.combinations(2) {
assert_eq!(combo.len(), 2);
}Required Associated Types§
Required Methods§
Sourcefn combinations(&self, k: usize) -> CombinationIter<'_, Self::Item> ⓘ
fn combinations(&self, k: usize) -> CombinationIter<'_, Self::Item> ⓘ
Returns an iterator over all k-element combinations.
use combinations::Combinations;
let items = ["a", "b", "c"];
let got: Vec<Vec<&&str>> = items.combinations(2).collect();
assert_eq!(got, [vec![&"a", &"b"], vec![&"a", &"c"], vec![&"b", &"c"]]);
// k=0 yields one empty combination
assert_eq!(items.combinations(0).count(), 1);
// k > len yields nothing
assert!(items.combinations(10).next().is_none());Sourcefn combinations_range(
&self,
range: impl RangeBounds<usize>,
) -> CombinationRangeIter<'_, Self::Item> ⓘ
fn combinations_range( &self, range: impl RangeBounds<usize>, ) -> CombinationRangeIter<'_, Self::Item> ⓘ
Returns an iterator over combinations of all sizes within range.
Accepts any RangeBounds<usize>: 0..=k, 1..3, .., etc.
Combinations are yielded in order of increasing size.
use combinations::Combinations;
// All subsets of size 1 or 2
let items = [1, 2, 3];
let got: Vec<Vec<&i32>> = items.combinations_range(1..=2).collect();
assert_eq!(got.len(), 6); // C(3,1) + C(3,2) = 3 + 3
// All 2^3 = 8 subsets
assert_eq!(items.combinations_range(..).count(), 8);Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.