0
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?

ruby Array#permutation メソッド

Posted at

Array#permutationとは

1.配列の順列を全て返す

arr = [1,4,6]
pp arr.permutation.to_a
結果
[[1, 4, 6], [1, 6, 4], [4, 1, 6], [4, 6, 1], [6, 1, 4], [6, 4, 1]]

引数に数字を渡すと、その長さの順列を返してくれます。

arr = [1,4,6]
pp arr.permutation(2).to_a
結果
[[1, 4], [1, 6], [4, 1], [4, 6], [6, 1], [6, 4]]

※範囲以上の数字を渡すとnilです。

arr = [1,4,6]
pp arr.permutation(4).to_a
結果
[]

また、返り値はArrayではなくEnumeratorが返るので、配列として取得してしまいたい場合はto_aが必要になります。

2.ブロックを渡す

ブロックを渡した場合、その場で結果を利用するのでto_aは必要ありません。
(Enumeratorは遅延評価で必要な時に結果を生成する)
渡された処理を結果配列の各要素に実行してくれます。

arr = [1, 4, 6]
result = []
arr.permutation(2) {|e| result << e}
pp result
結果
[[1, 4], [1, 6], [4, 1], [4, 6], [6, 1], [6, 4]]

競プロで、値が小さい全探索に利用できそうです。

0
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
0
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?