LoginSignup
4

More than 5 years have passed since last update.

[Groovy]複数のリストから全ての組み合わせを持ったリストを生成する

Posted at

概要

数学で言うところの順列(Permutation)と組み合わせ(Combination)です。
それぞれeachPermutationeachCombinationというメソッドがあります。

今回の例は単純に数字を使っていますが、例えば何かしらの検索サービスを実装する際に、Aの検索結果は100件で、AにBという検索条件を足した場合は80件、AにBとCとう検索条件を追加した場合は20件、といった使い方が出来るんじゃないのかな。。。と想像します。


// 組み合わせ
List combinationList = []
[[1,2], [3,4]].eachCombination { combinationList << it }
assert [[1,3], [2,3], [1,4], [2,4]] == combinationList


// 順列
List permutationList = []
[1, 2, 3].eachPermutation { permutationList << it }
assert  [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] == permutationList

// 組み合わせから順列を生成
List combinationToPermutation = []
combinationList.each { List combination ->
    combination.eachPermutation{ combinationToPermutation << it }

}

assert [[1, 3], [3, 1], [2, 3], [3, 2], [1, 4], [4, 1], [2, 4], [4, 2]] == combinationToPermutation

参考

eachCombination
eachPermutation

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
4