有人可以建議解決這個問題嗎?
我有多個清單。 我需要迭代這些列表中所有可能的值組合。 問題是我從中獲取值的列表數量是在運行時決定的。 因此,我無法為兩個清單編寫兩個巢狀「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”}
};