有人可以提出解决方案吗?
我有多个清单。 我需要遍历这些列表中所有可能的值组合。 问题在于,我从中获取值的列表的数量是在运行时确定的。 因此,我无法为两个列表编写两个嵌套的“ for”循环,然后为三个列表编写三个嵌套的“ for”循环。 我需要以某种方式传递\解析列表的名称(可能作为列表本身),然后遍历列表中的所有列表\值。
有任何想法吗?
在JMP认为您的递归太深之前,我不确定这能走多远,所以请先进行测试...如果列表太多,则使用堆栈的解决方法会稍微少一些。 但是,如果每个列表至少包含两个元素,那么我认为您首先会用光时间。
// the variable length list of variable length lists
L = {{"a", "b"}, {"c"}, {"d", "e", "f"}, {"g", "h", "i", "j"}};
result = {}; // a place to accumulate the results
p = {}; // a single result
// a recursive function to "nest the for loops"
generate = Function( {i}, // the "layer"
{j}, // the local for-loop counter
If( i > N Items( L ),
result[N Items( result ) + 1] = p; // you could just use p at this point
Return();
);
For( j = 1, j <= N Items( L[i] ), j += 1, // go through all the items at this layer
Insert Into( p, L[i][j] ); // add each to the single result
Recurse( i + 1 ); // go to next layer
Remove From( p ); // remove from the single result
);
);
generate( 1 ); // run the recursive function
Show( result );结果= {
{“ a”,“ c”,“ d”,“ g”},
{“ a”,“ c”,“ d”,“ h”},
{“ a”,“ c”,“ d”,“ i”},
{“ a”,“ c”,“ d”,“ j”},
{“ a”,“ c”,“ e”,“ g”},
{“ a”,“ c”,“ e”,“ h”},
{“ a”,“ c”,“ e”,“ i”},
{“ a”,“ c”,“ e”,“ j”},
{“ a”,“ c”,“ f”,“ g”},
{“ a”,“ c”,“ f”,“ h”},
{“ a”,“ c”,“ f”,“ i”},
{“ a”,“ c”,“ f”,“ j”},
{“ b”,“ c”,“ d”,“ g”},
{“ b”,“ c”,“ d”,“ h”},
{“ b”,“ c”,“ d”,“ i”},
{“ b”,“ c”,“ d”,“ j”},
{“ b”,“ c”,“ e”,“ g”},
{“ b”,“ c”,“ e”,“ h”},
{“ b”,“ c”,“ e”,“ i”},
{“ b”,“ c”,“ e”,“ j”},
{“ b”,“ c”,“ f”,“ g”},
{“ b”,“ c”,“ f”,“ h”},
{“ b”,“ c”,“ f”,“ i”},
{“ b”,“ c”,“ f”,“ j”}
};