all_combinations/
lib.rs

1
2
3pub struct AllCombinations<'a,T> {
4    base: &'a[T],         // it is a dictionary
5    data: Vec<usize>,     // current combinations
6    base_max_id: usize,   // base.len()-1
7    n: usize,             // current length
8    none: bool,           //
9}
10
11impl<'a,T> AllCombinations<'a,T> {
12    /// create new brute force iterator
13    pub fn new_fixed_size(base: &'a[T], size: usize) -> Self {
14        Self {
15            base: base,
16            base_max_id: base.len()-1,
17            data: vec![0;size],
18            n: size,
19            none: false,
20        }
21    }
22}
23
24impl<'a,T:Clone> Iterator for AllCombinations<'a,T> {
25    type Item = Vec<T>;
26
27    fn next(&mut self) -> Option<Self::Item> { 
28        if self.none { return None; }
29
30        let mut v = Vec::with_capacity(self.data.len());
31        for i in &self.data { v.push(self.base[*i].clone()) }
32
33        self.none = true;
34        for i in (0..=self.n-1).rev() {
35            if self.data[i]==self.base_max_id { self.data[i]=0; } else { self.data[i]+=1; self.none = false; break; }
36        }
37        
38        Some(v)
39    }
40}
41
42
43#[test]
44fn t1() {
45    let base = b"01234";
46    let mut all = AllCombinations::new_fixed_size(base, 2);
47    assert_eq!(all.next(), Some(b"00".to_vec()));
48    assert_eq!(all.next(), Some(b"01".to_vec()));
49    assert_eq!(all.next(), Some(b"02".to_vec()));
50    assert_eq!(all.next(), Some(b"03".to_vec()));
51    assert_eq!(all.next(), Some(b"04".to_vec()));
52    assert_eq!(all.next(), Some(b"10".to_vec()));
53    assert_eq!(all.next(), Some(b"11".to_vec()));
54    assert_eq!(all.next(), Some(b"12".to_vec()));
55    assert_eq!(all.next(), Some(b"13".to_vec()));
56    assert_eq!(all.next(), Some(b"14".to_vec()));
57    assert_eq!(all.next(), Some(b"20".to_vec()));
58    assert_eq!(all.next(), Some(b"21".to_vec()));
59    assert_eq!(all.next(), Some(b"22".to_vec()));
60    assert_eq!(all.next(), Some(b"23".to_vec()));
61    assert_eq!(all.next(), Some(b"24".to_vec()));
62    assert_eq!(all.next(), Some(b"30".to_vec()));
63    assert_eq!(all.next(), Some(b"31".to_vec()));
64    assert_eq!(all.next(), Some(b"32".to_vec()));
65    assert_eq!(all.next(), Some(b"33".to_vec()));
66    assert_eq!(all.next(), Some(b"34".to_vec()));
67    assert_eq!(all.next(), Some(b"40".to_vec()));
68    assert_eq!(all.next(), Some(b"41".to_vec()));
69    assert_eq!(all.next(), Some(b"42".to_vec()));
70    assert_eq!(all.next(), Some(b"43".to_vec()));
71    assert_eq!(all.next(), Some(b"44".to_vec()));
72    assert_eq!(all.next(), None);
73    assert_eq!(all.next(), None);
74}