I need some help writing a predicate in Prolog that, given a number as input, returns a list of lists with numbers that add up to it.
Let's call the predicate addUpList/2, it should work like this:
?- addUpList(3,P).
P = [[1,2], [2,1], [1,1,1]]. % expected result
I'm having so much trouble figuring this out I'm beginning to think it's impossible. Any ideas? Thanks in advance.
There are plenty of great answers to this question already, but here is another solution to this problem for you to consider. This program differs from the others in that it is very efficient, and generates non-redundant solutions of lists which are assumed to represent sets of integers which add up to the specified number.
Your implementation of
addUpList/2
can be achieved by:Which should give you the following behaviour:
Note that the list containing one
2
and two1
s only appears once in this result set; this is becausegen/4
computes unique sets of integers which add up to the specified number.This answer is somewhere between @Kaarel's answer and @sharky's "efficient" answer.
Like @sharky's code, we impose an ordering relation between adjacent list items to restrict the size of the solution space---knowing how to inflate it if we ever need to. So the solution sets of
break_down/2
andgen/2
by @sharky are equal (disregarding list reversal).And as for performance, consider:
Try this:
Let me know what marks I get. :-)
The example given in the Question suggests that compositions (ordered partitions) of any positive integer N ≤ 10 are wanted. Note however that the solution [3] for N=3 seems to have been omitted/overlooked. The number of compositions of N is 2^(N-1), so N=10 gives a long list but not an unmanageable one.
It is also desired to collect all such solutions into a list, something that
findall/3
can do generically after we write a predicatecomposition/2
that generates them.The idea is to pick the first summand, anything between 1 and N, subtract it from the total and recurse (stopping with an empty list when the total reaches zero). SWI-Prolog provides a predicate
between/3
that can generate those possible first summands, and Amzi! Prolog provides a similar predicatefor/4
. For the sake of portability we write our own version here.Given the above Prolog source code, compiled or interpreted, a list of all solutions can be had in this way:
Of course some arrangement of such a list of solutions or the omission of the singleton list might be required for your specific application, but this isn't clear as the Question is currently worded.
The rule
num_split/2
generates ways of splitting a number into a list, where the first elementX
is any number between1
andN
and the rest of the list is a split ofN-X
.In order to get all such splits, just call
findall/3
onnum_split/2
.Usage example:
See also the post by @hardmath which gives the same answer with a bit more explanation.