組み合わせ \(n!\)

For each \(\{ x_i : 0 \leq i \lt n, 0 \leq x_i \lt n, x_i \ne x_j \}\)

Rust

struct Permutation { n: usize, idx: usize }
impl Permutation {
    fn new(n: usize) -> Permutation {
        Permutation { n: n, idx: 0 }
    }
}
impl Iterator for Permutation {
    type Item = Vec<usize>;
    fn next(&mut self) -> Option<Vec<usize>> {
        let mut r = vec![0; self.n];
        let mut idx = self.idx;
        for k in 1..self.n {
            r[k] = idx % (k + 1);
            idx /= k + 1;
        }
        if idx > 0 { return None }
        r.reverse();
        let mut b = vec![true; self.n];
        b[r[0]] = false;
        for k in 1..self.n {
            let mut count = 0;
            for j in 0..self.n {
                if b[j] {
                    if count == r[k] {
                        r[k] = j;
                        b[j] = false;
                        break;
                    }
                    count += 1;
                }
            }
        }
        self.idx += 1;
        return Some(r)
    }
}

Example

fn main() {
    let n = 3;
    let mut count = 0;
    for a in Permutation::new(n) {
        count += 1;
        println!("{:?}", a);
    }
    println!("{:?}", count);
}
[0, 1, 2]
[0, 2, 1]
[1, 0, 2]
[1, 2, 0]
[2, 0, 1]
[2, 1, 0]
6

C++ (STL)

vector<int> v(3);
rep (i, v.size()) v[i] = i;

do {
  cout << v << endl;
} while (next_permutation(begin(v), end(v)));
0 1 2
0 2 1
1 0 2
1 2 0
2 0 1
2 1 0