Get a list of sets where the sum of each set is X

I am trying to figure out how to generate a list of sets, where each set has a length N and the sum of each set is X.

I found this code:

num_split(0,[]).
num_split(N, [X | List]):-
   between(1,N,X),
   plus(X,Y,N),
   num_split(Y,List).

And I can use this to get a list of sets with the sum of X:

num_split(6,List),length(List,5).
List = [1, 1, 1, 1, 2] ;
List = [1, 1, 1, 2, 1] ;
List = [1, 1, 2, 1, 1] ;
List = [1, 2, 1, 1, 1] ;
List = [2, 1, 1, 1, 1] ;
false.

The problem is that these are all permutations, and I'm looking for combinations. The result I'm looking for should be something like get_combos(Sum,Length,List):

get_combos(6,2,List).
List = [5,1];
List = [4,2];
List = [3,3];
false.

Any pointers?

+3
source share
2 answers

If you have access to the CLP (FD) library , you can use this code:

:- [library(clpfd)].

get_combos(Sum, Length, List) :-
    length(List, Length),
    List ins 1 .. Sum,
%   all_distinct(List), not really useful here
    sum(List, #=, Sum),
    chain(List, #<),
    label(List).

Test:

?- get_combos(10,3,L).
L = [1, 2, 7] ;
L = [1, 3, 6] ;
L = [1, 4, 5] ;
L = [2, 3, 5] ;

Perhaps I misunderstood your question. Use this chain

...
chain(List, #=<),
....

to get possible duplicate values:

?- get_combos(10,3,L).
L = [1, 1, 8] ;
L = [1, 2, 7] ;
L = [1, 3, 6] ;
L = [1, 4, 5] ;
L = [2, 2, 6] ;
L = [2, 3, 5] ;
L = [2, 4, 4] ;
L = [3, 3, 4] ;
false.
+3
source

" " .

:

is_combination([]).
is_combination([_]).
is_combination([A,B|List]) :- A =< B, is_combination([B|List]).

get_combos(Sum, Length, List) :-
    num_split(Sum, Length, List),
    is_combination(List).

, num_split/3 , :

get_combos(_, 0, []).
get_combos(Sum, 1, [Sum]).
get_combos(Sum, Length, [A, B|List]) :-
    between(1, Sum, A),
    plus(A, NextSum, Sum),
    plus(1, NextLength, Length),
    get_combos(NextSum, NextLength, [B|List]),
    A =< B.

, , - (= <), , .

+1

All Articles