Rubyで順列や組み合わせを生成する
プログラマの数学5章を読んでいて、順列や組み合わせを生成するメソッドがRubyにあるか気になり調べたところ見つかった
cf. https://www.amazon.co.jp/dp/B079JLW5YN/ref=dp-kindle-redirect?_encoding=UTF8&btkr=1
Array#permutation
https://docs.ruby-lang.org/ja/latest/method/Array/i/permutation.html
引数で渡されたサイズの順列を生成する
また、それを引数としてブロックを実行する
a = [1, 2, 3]
a.permutation.to_a
# => [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
a.permutation(1).to_a
# => [[1], [2], [3]]
a = [1, 2]
a.permutation{|item| p item}
# => [1, 2]
# [2, 1]
Array#combination
https://docs.ruby-lang.org/ja/latest/class/Array.html#I_COMBINATION
引数で指定されたサイズの組み合わせを生成する
a = [1, 2, 3, 4]
a.combination(1).to_a #=> [[1],[2],[3],[4]]
a.combination(2).to_a #=> [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
階乗するメソッドは存在しなかった
ので、自作する必要がある
def factorial(n)
(1..n).inject(&:*)
end