1
0

More than 1 year has passed since last update.

[Ruby] Array#permutation

Last updated at Posted at 2021-09-20

はじめに

Rubyのpermutationメソッドについて簡単にまとめたいと思います。
よろしくお願いします。

permutationメソッド

これは配列の中の組み合わせを全て作ってくれます。
返し方は配列の中に配列を作って一つの組み合わせを表現します。

また、要素が同じで順番が違っていた場合も違う組み合わせとして扱われます。

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 = [1, 2, 3]
a.permutation(2).to_a

=> [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]

参考: https://docs.ruby-lang.org/ja/latest/method/Array/i/permutation.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