mic*_*man 6 groovy combinatorics
是否有方法或一些智能方法易于阅读,以便在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
Run Code Online (Sandbox Code Playgroud)
随意发布替代解决方案.我仍然在寻找更好的可读性(它在非开发人员的脚本中使用)和性能(没有不必要的迭代).
Kaf*_*eif 11
我不太确定可读性,但这应该可以解决问题.
def e = ['a', 'b', 'c']
def result = [e, e].combinations().findAll { a, b ->
a < b
}
assert [['a', 'b'], ['a', 'c'], ['b', 'c']] == result
Run Code Online (Sandbox Code Playgroud)
请注意,如果元素在列表中出现两次,则其组合也会出现两次.如果不需要,最后添加'.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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2302 次 |
| 最近记录: |