Groovy中的实组合

Groovy中的实组合,groovy,combinatorics,Groovy,Combinatorics,在Groovy中,有没有一种简单易读的方法或智能方法来创建一个元素库?我知道Iterable#组合或GroovyCollections#组合,但据我目前所知,它会通过重复进行部分排列。参见示例 // Groovy combinations result def e = ['a', 'b', 'c'] def result = [e, e].combinations() assert [['a', 'a'], ['b', 'a'], ['c', 'a'], ['a', 'b'], ['b', 'b

在Groovy中,有没有一种简单易读的方法或智能方法来创建一个元素库?我知道
Iterable#组合
GroovyCollections#组合
,但据我目前所知,它会通过重复进行部分排列。参见示例

// Groovy combinations result
def e = ['a', 'b', 'c']
def result = [e, e].combinations()
assert [['a', 'a'], ['b', 'a'], ['c', 'a'], ['a', 'b'], ['b', 'b'], ['c', 'b'], ['a','c'], ['b', 'c'], ['c', 'c']] == result

// What I'm looking for
def e = ['a', 'b', 'c']
def result = ???
assert [['a', 'b'], ['a', 'c'], ['b', 'c']] == result
请随意发布替代解决方案。我仍然在寻找更好的可读性(它用于非开发人员的脚本)和性能(不需要不必要的迭代)


我对可读性不是很确定,但这应该可以做到

def e = ['a', 'b', 'c']
def result = [e, e].combinations().findAll { a, b ->
    a < b
}

assert [['a', 'b'], ['a', 'c'], ['b', 'c']] == result
def e=['a','b','c']
def result=[e,e].combinations().findAll{a,b->
a

注意,如果一个元素在列表中出现两次,那么它的组合也会出现两次。如果不需要,请在末尾添加“.unique()”

这里有一种更通用的方法,允许您为nCr组合指定“r”值。它通过在集合中存储置换来实现这一点,集合提供唯一性:

// returns combinations of the input list of the provided size, r
List combinationsOf(List list, int r) {
    assert (0..<list.size()).contains(r) // validate input
    def combs = [] as Set
    list.eachPermutation {
        combs << it.subList(0, r).sort { a, b -> a <=> b }
    }
    combs as List
}

// the test scenario...
def e = ['a', 'b', 'c']
def result = combinationsOf(e, 2)
assert [['a', 'b'], ['a', 'c'], ['b', 'c']] == result
//返回所提供大小的输入列表的组合,r
列表组合sof(列表,int r){

断言(0..谢谢。只有一件事。您甚至不必测试a!=b,因为此条件包含在a