【发布时间】:2018-03-16 05:12:35
【问题描述】:
假设我有一个随机长度的列表,例如:
L = [190, 20, 80, 200, 10].
有什么方法可以得到输出列表中所有可能的元素组合,使它们的总和小于或等于给定值?
例如find_elements(MaxValue, InputList, OutputList)。
MaxValue = 200 的可能解决方案:
OutputList = [190, 10]
OutputList = [200]
OuputList = [20, 80, 10]
到目前为止,我的代码如下所示:
solutions(_, [], [], _).
solutions(MaxValue, [H|T], OutputList, Acc):-
Z is H + Acc,
Z > MaxValue,
solutions(MaxValue, T, OutputList, Acc), !.
solutions(MaxValue, [H|T], [H|T2], Acc):-
Z is H + Acc,
Z =< MaxValue,
solutions(MaxValue, T, T2, Z).
solutions(MaxValue, Inputlist, OutputList):-
solutions(MaxValue, Inputlist, OutputList, 0).
如果我打电话
solutions(200, [190, 250, 3, 4, 180, 10], X)
我明白了:
X = [190, 3, 4]
但X = [3, 4, 180] 也是如此,X = [180, 10] 也是如此。我想把它们都作为解决方案。
提前致谢!
【问题讨论】:
-
是的,有可能。到目前为止,您尝试过什么?
-
我尝试使用累加器变量递归遍历列表,该变量从左到右将元素相加,但这不是我想要的。如果我使用 MaxValue = 200,我会得到 OutputList = [190]。但也有其他元素组合可以满足这一点,例如 OutputList = [20, 80, 10]。
-
编辑您的问题并显示您的编码尝试以及您遇到的问题。
-
我已经更新了问题并添加了代码。谢谢。
-
A hint。您可能需要对其进行调整,因为这将为您提供所有组合的每个顺序;)
标签: prolog