prolog - How to create a list of fixed length and sums up to a certain number while choosing from its elements from other list -
assuming have list
l=[1,2,3]
want create listo
length ofo
n
, total sum of elementss
has created using elementsl
if contain duplicates.examples
n=5
,s=7
:o=[2,2,1,1,1] o=[2,1,2,1,1] o=[3,1,1,1,1] o=[1,3,1,1,1]
here's variant similar @wouterbeek's solution doesn't use separate accumulator:
summate_tokens(types, sum, n, [x|t]) :- n > 0, member(x, types), sum1 sum - x, % subtract running sum n1 n - 1, summate_tokens(types, sum1, n1, t). summate_tokens(_, 0, 0, []).
it implicitly handles length of solution counter, n
. work kind of numbers in types
argument.
with results:
?- summate_tokens([1,2,3], 7, 5, tokens). tokens = [1, 1, 1, 1, 3] ; tokens = [1, 1, 1, 2, 2] ; tokens = [1, 1, 1, 3, 1] ; tokens = [1, 1, 2, 1, 2] ; tokens = [1, 1, 2, 2, 1] ; tokens = [1, 1, 3, 1, 1] ; tokens = [1, 2, 1, 1, 2] ; tokens = [1, 2, 1, 2, 1] ; tokens = [1, 2, 2, 1, 1] ; tokens = [1, 3, 1, 1, 1] ; tokens = [2, 1, 1, 1, 2] ; tokens = [2, 1, 1, 2, 1] ; tokens = [2, 1, 2, 1, 1] ; tokens = [2, 2, 1, 1, 1] ; tokens = [3, 1, 1, 1, 1] ; false. ?-
if types
, sum
limited non-negative numbers, including sum1 >= 0
after sum1 sum - x
improve performance.
Comments
Post a Comment