タグ

ブックマーク / simanman.hatenablog.com (1)

  • Rubyでの順列、組み合わせ。 - simanのブログ

    Rubyでは「順列」と「組み合わせ」をArrayクラスのcombinationメソッドとpermutationメソッドを用いることで、簡単に求めることができます。 array = [1,2,3,4] p array.combination(3).to_a [[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]combinationの引数は選び出す要素の個数を指定する。 array = [1,2,3] p array.permutation(3).to_a [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]両方とも便利なメソッドです。 また、要素の重複を許可する場合は repeated_combination や repeated_permutation が利用できます。 なぜ

    Rubyでの順列、組み合わせ。 - simanのブログ
  • 1