Posted at

雑に組み合わせ数を得る

4C2のような4要素から2要素組み合わせを重複無しで得るにはArray#combinationを使う。

irb(main):034:0> (1..4).to_a.combination(2).count

=> 6
irb(main):035:0> (1..4).to_a.combination(2).to_a
=> [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]

重複あり組み合わせならArray#repeated_combination

irb(main):037:0> (1..4).to_a.repeated_combination(2).count

=> 10
irb(main):038:0> (1..4).to_a.repeated_combination(2).to_a
=> [[1, 1], [1, 2], [1, 3], [1, 4], [2, 2], [2, 3], [2, 4], [3, 3], [3, 4], [4, 4]]
irb(main):039:0>


参考

http://rurema.clear-code.com/2.3.0/method/Array/i/repeated_combination.html

http://rurema.clear-code.com/2.3.0/method/Array/i/combination.html