yiskw note

機械学習やプログラミングについて気まぐれで書きます

【Rust】順列,組み合わせ,重複組み合わせを列挙する


Rustで順列や組み合わせ,重複組み合わせを列挙する方法がわからなかったので,
調べた結果をこちらにメモしておきます.

方法

Rustのitertools::Itertoolsトレイトにはそれぞれ順列,組み合わせ,重複組み合わせを列挙するメソッドである,
permutations, combinations, combinations_with_replacementが提供されています.

use itertools::Itertools;

fn main() {
    // nPr (n = 3, r = 2)
    println!("Permutation.");
    for perm in (0..3).permutations(2) {
        println!("{:?}", perm);
    }

    // nCr (n = 3, r = 2)
    println!("\nCombination.");
    for comb in (0..3).combinations(2) {
        println!("{:?}", comb);
    }

    // nHr (n = 3, r = 2)
    println!("\nCombination with replacement.");
    for comb in (0..3).combinations_with_replacement(2) {
        println!("{:?}", comb);
    }
}
Permutation.
[0, 1]
[0, 2]
[1, 0]
[1, 2]
[2, 0]
[2, 1]

Combination.
[0, 1]
[0, 2]
[1, 2]

Combination with replacement.
[0, 0]
[0, 1]
[0, 2]
[1, 1]
[1, 2]
[2, 2]

Reference