title: Prolog: Arrangements of k elements with sum of elements S
body: <p>I am trying to compute arrangements of <code>K</code> elements in Prolog, where the sum of their elements is equal to a given <code>S</code>. So, I know that arrangements can be computed by finding the combinations and then permute them. I know how to compute combinations of <code>K</code> elements, something like:</p>
  
  <pre><code>comb([E|_], 1, [E]).
  comb([_|T], K, R) :-
     comb(T, K, R).
  comb([H|T], K, [H|R]) :-
     K &gt; 1,
     K1 is K-1,
     comb(T, K1, R).
  </code></pre>
  
  <p>The permutations of a list, having the property that the sum of their elements is equal to a given S, I know to compute like this:</p>
  
  <pre><code>insert(E, L, [E|L]).
  insert(E, [H|T], [H|R]) :-
     insert(E, T, R).
  
  perm([], []).
  perm([H|T], P) :-
     perm(T, R),
     insert(H, R, P).
  
  sumList([], 0).
  sumList([H], H) :-
     number(H).
  sumList([H|Tail], R1) :-
     sumList(Tail, R),
     R1 is R+H.
  
  perms(L, S, R) :-
     perm(L, R),
     sumList(R, S1),
     S = S1.
  
  allPerms(L, LP) :-
     findall(R, perms(L,R), LP).
  </code></pre>
  
  <p>The problem is that I do not know how to combine them, in order to get the arrangements of <code>K</code> elements, having the sum of elements equal to a given <code>S</code>. Any help would be appreciated.</p>