是否有易于阅读的方法或一些聪明的方法来制作 combination Groovy 中的元素?我知道 Iterable#combinations
或 GroovyCollections#combinations
但它使部分排列重复,因为我到目前为止所理解的。参见示例。
// 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
Feel free to post alternate solutions. I'm still looking for better readability (it's used in script for non-developers) and performance (w/o unnecessary iterations).
最佳答案
我不太确定可读性,但这应该可以解决问题。
def e = ['a', 'b', 'c']
def result = [e, e].combinations().findAll { a, b ->
a < b
}
assert [['a', 'b'], ['a', 'c'], ['b', 'c']] == result
请注意,如果一个元素在列表中出现两次,其组合也将出现两次。如果不需要,请在末尾添加“.unique()”
关于groovy - Groovy 中的真正组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26272916/