Prolog search for possible combination for subtracting 2 elements from a list

前端 未结 2 810
情深已故
情深已故 2021-01-23 12:34

This is an extended problem from this page. Prolog possible removal of elements in a list

For example, for a list X = [1,2,3], I can subtract like following:

sub

2条回答
  •  时光取名叫无心
    2021-01-23 12:48

    I would use 2 procedures.

    The first one takes an item from the list, computes a number equal or lesser than it and then calls second procedure to subtract that number from another item in the remaining list.

    You have to take care of border cases (if computed number is equal to item, then remove the item altogether), thus I use a different clause for those cases.

    subt_comb([N|Tail], [NX|NTail]):-
      succ(N1, N),
      between(1, N1, NX),
      subt_comb1(Tail, NX, NTail).
    subt_comb([N|Tail], NTail):-
      subt_comb1(Tail, N, NTail).
    subt_comb([N|Tail], [N|NTail]):-
      subt_comb(Tail, NTail).
    
    subt_comb1([M|Tail], N, [NM|Tail]):-
      M > N,
      NM is M - N.
    subt_comb1([N|Tail], N, Tail).
    subt_comb1([M|Tail], N, [M|NTail]):-
      subt_comb1(Tail, N, NTail).
    

    Sample:

    ?- subt_comb([1,2,3], Y).
    Y = [1, 3] ;
    Y = [2, 2] ;
    Y = [1, 1, 2] ;
    Y = [1, 1] ;
    false.
    

提交回复
热议问题