LoginSignup
9
6

More than 5 years have passed since last update.

再帰や繰り返しが面倒な順列/組み合わせの生成もRubyなら一瞬

Last updated at Posted at 2012-07-01

順列なら Array#permutation

perm = (1..3).to_a.permutation(3)
perm.to_a
# => [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

組み合わせなら Array#combination

comb = (1..4).to_a.combination(2)
comb.to_a
# => [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]

どちらも引数無しなら Enumerator が返ってくる。各要素について処理したいならブロックも渡せる。

これで順列/組み合わせで再帰に悩む必要はなくなった!やったね!

9
6
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
9
6