ven*_*sai 4 recursion groovy list
我有一个2d列表,其中行数介于1到5之间,每行中的多个元素是动态的.我们假设我有一个列表
values = [[1,2,3], [4,5],[6,7,8,9]];
result = [[1,4,6],[1,4,7],[1,4,8],[1,4,9],[1,5,6],[1,5,7],[1,5,8],[1,5,9],[2,4,6],[2,4,7],[2,4,8],[2,4,9],[2,5,6],[2,5,7],[2,5,8],[2,5,9],[3,4,6],[3,4,7],[3,4,8],[3,4,9],[3,5,6],[3,5,7],[3,5,8],[3,5,9]]
Run Code Online (Sandbox Code Playgroud)
值是我的输入,我需要以结果的格式输出.
我尝试以递归方式实现函数但失败了.我的功能是
import groovy.transform.Field
List lines = [];
def function(row, col, lines)
{
if(row >= values.size())
{
log.info("This should go inside result: " + lines);
return;
}
if(col >= values[row].size())
{
return;
}
lines << values[row][col];
function(row+1,col,lines);
lines.pop();
function(row,col+1,lines);
return;
}
@Field
List values = [[1,2,3],[4,5],[6,7,8,9]];
@Field
List lst = [];
for(int i=0; i<values[0].size(); i++)
function(0, i, lines)
Run Code Online (Sandbox Code Playgroud)
Groovy有一个内置的集合函数combinations(),可以从元素列表列表中生成所有可能的组合.
用法示例:
Run Code Online (Sandbox Code Playgroud)assert [['a', 'b'],[1, 2, 3]].combinations() == [['a', 1], ['b', 1], ['a', 2], ['b', 2], ['a', 3], ['b', 3]]
您可以values从初始脚本中调用此方法:
def values = [[1,2,3], [4,5],[6,7,8,9]]
def expected = [[1,4,6],[1,4,7],[1,4,8],[1,4,9],[1,5,6],[1,5,7],[1,5,8],[1,5,9],[2,4,6],[2,4,7],[2,4,8],[2,4,9],[2,5,6],[2,5,7],[2,5,8],[2,5,9],[3,4,6],[3,4,7],[3,4,8],[3,4,9],[3,5,6],[3,5,7],[3,5,8],[3,5,9]]
def result = values.combinations()
assert ((expected as Set) == (result as Set))
Run Code Online (Sandbox Code Playgroud)
import groovy.transform.CompileStatic
import groovy.transform.TailRecursive
@TailRecursive
@CompileStatic
<T> List<List<T>> combinations(final List<List<T>> xss, final List<List<T>> result = [[]]) {
return !xss ? result : combinations(xss.tail(), process(xss.head(), result))
}
@CompileStatic
<T> List<List<T>> process(final List<T> xs, final List<List<T>> result) {
return result.inject([]) { yss, ys -> yss + xs.collect { x -> ys + x } }
}
def values = [[1,2,3], [4,5],[6,7,8,9]]
def expected = [[1,4,6],[1,4,7],[1,4,8],[1,4,9],[1,5,6],[1,5,7],[1,5,8],[1,5,9],[2,4,6],[2,4,7],[2,4,8],[2,4,9],[2,5,6],[2,5,7],[2,5,8],[2,5,9],[3,4,6],[3,4,7],[3,4,8],[3,4,9],[3,5,6],[3,5,7],[3,5,8],[3,5,9]]
assert combinations(values) == expected
Run Code Online (Sandbox Code Playgroud)