Ruby

rubyで順列・組合せ

順列・組合せのメソッドを見つけたのでご報告でございます:horse::unicorn:

順列(nPr)

[1,2,3].permutation(2) do |a, b|
  printf("(%d, %d) ", a, b)
end
# printfの出力
# (1, 2) (1, 3) (2, 1) (2, 3) (3, 1) (3, 2)

重複順列

[1,2,3].repeated_permutation(2) do |a, b|
  printf("(%d, %d) ", a, b)
end
# printfの出力
# (1, 1) (1, 2) (1, 3) (2, 1) (2, 2) (2, 3) (3, 1) (3, 2) (3, 3)

組合せ(nCr)

[1,2,3].combination(2) do |a, b|
  printf("(%d, %d) ", a, b)
end
# printfの出力
# (1, 2) (1, 3) (2, 3)

重複組合せ

[1,2,3].repeated_combination(2) do |a, b|
  printf("(%d, %d) ", a, b)
end
# printfの出力
# (1, 1) (1, 2) (1, 3) (2, 2) (2, 3) (3, 3)