summaryrefslogtreecommitdiff
path: root/src/permutations.rs
blob: 7b8e4d37132720810829a4b9dacb926fc81f9f72 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
use permutohedron::{Heap, LexicalPermutation};

pub trait PermutationGenerator {
    fn permutations(n: u32) -> Vec<Vec<u32>>;
}

pub struct HeapsPermutations;

impl PermutationGenerator for HeapsPermutations {
    fn permutations(n: u32) -> Vec<Vec<u32>> {
        Heap::<'_, Vec<u32>, _>::new(&mut (1..=n).collect()).collect()
    }
}

pub struct LexicalPermutations {
    state: Vec<u32>,
    is_ended: bool,
}

impl Iterator for LexicalPermutations {
    type Item = Vec<u32>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.is_ended {
            None
        } else {
            self.is_ended = self.state.next_permutation();
            Some(self.state.clone())
        }
    }
}

impl LexicalPermutations {
    fn new(n: u32) -> Self {
        Self {
            state: (1..=n).collect(),
            is_ended: false
        }
    }
}

impl PermutationGenerator for LexicalPermutations {
    fn permutations(n: u32) -> Vec<Vec<u32>> {
        Self::new(n).collect()
    }
}