我想获取任意数量的列表并返回元素组合列表,但只组合每个列表中的一个元素。我所拥有的只是sudo代码,因为我不知道从哪里开始。
我确实在Combining the elements of 2 lists的问题中找到了该程序的解决方案,但我不明白scala代码。我正在用Tcl编写我的程序,但是如果你能帮助我随意用java或python或伪代码或其他任何东西写你的答案。任何人都可以帮我把下面的伪代码带到生活中吗?
例如:
# example: {a b} {c} {d e}
# returns: {a c d} {a c e} {b c d} {b c e}
# how?
# example: {a b} {c} {d e}
# iters: 0 0 0
# 0 0 1
# 1 0 0
# 1 0 1
#
#
# set done false
#
# while {!done} {
#
# list append combination_of_list due to iteration counts
#
# foreach list $lists {
# increment the correct count (specifically {0->1} {0->0} {0->1}) }
# reset the approapraite counts to 0
# }
#
# if all the counts in all the lists are at or above their max {
# set done true
# }
# }
答案 0 :(得分:1)
这是一个描述生成所有组合的算法的伪代码:
list_of_lists = {{a b}{c}{d e}}
def copy(list):
copy = {}
for element in list:
copy.add(element)
return copy;
def combine(list1, list2):
combinations = {}
for item1 in list1:
for item2 in list2:
combination = copy(item1)
combination.add(item2)
combinations.add(combination)
return combinations
results = {{}}
while list_of_lists.length>0:
results = combine(results, list_of_lists[0])
list_of_lists.remove(0)
首先将{{}}
与{a b c}
合并
产生{{a} {b}}
的{{1}}将与{c}
结合,在下一次迭代中生成{{a c} {b c}}
等。
<强>更新强> Javascript版本:
var list_of_lists = [["a", "b"],["c"],["d", "e"]];
function copy(list) {
var copy = [];
for (element of list) {
copy.push(element);
}
return copy;
}
function combine(list1, list2) {
var combinations = [];
for (let item1 of list1) {
var combination = copy(item1);
for (let item2 of list2){
combination.push(item2);
combinations.push(combination);
}
}
return combinations;
}
results = [[]]
while (list_of_lists.length>0) {
results = combine(results, list_of_lists[0]);
list_of_lists.splice(0,1);
}
console.log(results);
答案 1 :(得分:1)
本页讨论了各种Tcl解决方案:Cartesian product of a list of lists
Donal Fellows在页面末尾介绍了这种变化:
proc product args {
set xs {{}}
foreach ys $args {
set result {}
foreach x $xs {
foreach y $ys {
lappend result [list {*}$x $y]
}
}
set xs $result
}
return $xs
}
像这样运行会得到结果:
% product {a b} {c} {d e}
{a c d} {a c e} {b c d} {b c e}