1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

雑に組み合わせ数を得る

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

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?