1
2

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の順列操作!permutationメソッド

Posted at

はじめに

配列操作はプログラミングで頻繁に登場する基本的なスキルですが少し複雑。ですが、Rubyのpermutationというメソッドを使えば、驚くほど簡単に順列を生成することができることを知りました。

本記事では、Rubyのpermutationメソッドの使い方を具体例とともに分かりやすく解説したいと思います。「全順列を取得する方法」や「部分的な順列の生成」、さらにはEnumeratorを活用した使い方も挙げたいと思います!


permutationメソッドとは?

permutationは、Rubyの配列クラスに定義されている便利なメソッドになります。
このメソッドを使うことで、配列内の要素を並べ替えたすべての順列を簡単に生成できます。


使い方と具体例

  1. 基本的な使い方
    ますは、配列のすべての要素を使った順列を生成する基本的な例になります

    arr = [1, 2, 3]
    
    arr.permutation do |perm|
      p perm
    end
    

    出力例:

    [1, 2, 3]
    [1, 3, 2]
    [2, 1, 3]
    [2, 3, 1]
    [3, 1, 2]
    [3, 2, 1]
    

  2. 部分的な順列を生成
    引数を指定することで、部分的な順列を生成できます

    arr = [1, 2, 3]
    
    arr.permutation(2) do |perm|
      p perm
    end
    

    出力例:

    [1, 2]
    [1, 3]
    [2, 1]
    [2, 3]
    [3, 1]
    [3, 2]
    

  3. Enumeratorを活用
    ブロックを使わずにEnumeratorを返して操作する方法

    arr = [1, 2, 3]
    
    perms = arr.permutation(2) # permutation(2) は Enumerator を返す
    p perms.to_a # Enumerator の中身を配列に変換して出力
    

    出力例:

    [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]
    

Enumerator とは何か?

Enumerator は「中身を順番に取り出せる仕組み」を持つオブジェクトです。

  • 上記例では、arr.permutation(2) が返す perms が Enumerator

注意点

  • 要素数が多い場合の計算量

    配列の要素数が多いと、順列の数は**階乗(n!)**で増加します。

    例えば、10要素の配列では、10! = 3,628,800通りもの順列が生成されます。

  • 引数が要素数より大きい場合

    空の配列が返されます。

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

まとめ

Rubyのpermutationメソッドを活用することで、配列の並べ替えを簡単に実現できることを知ることができました。今回の記事が何か参考になれば幸いです。

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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?