Search code examples
prologswi-prolog

using greedy algorithm search in lists


Given a list of positive integer Items whose elements are guaranteed to be in sorted ascending order, and a positive integer Goal, and Output is a list of three elements [A,B,C] taken from items that together add up to goal. The Output must occur inside the items list in that order (ascending order).

ex:

?- threeSum([3,8,9,10,12,14],27,Output).
Output=[8,9,10];
Output=[3,10,14].

someone helped me to reach this to this code but it gives me singleton variables:[Input,Items] ,it didnt work although iam not quite sure if this is a greedy algorithm search or not ?

 threeSum(Input,Goal,[A,B,C]):-
  permutation(Items, [A,B,C|Rest]),
  msort([A,B,C],[A,B,C]),
  msort(Rest,Rest),
  sum_list([A,B,C],Goal).

Solution

  • nums_goal_answer(Input, Goal, [A,B,C]) :-
        length(Input, InputLen),    
        reverse(Input, RInput),     % 'greedy' interpreted as 'prefer larger values first'.
                                    % and larger values are at the end.
    
        between( 1, InputLen, N1),   
        between(N1, InputLen, N2),  % three nested for-loops equivalent.
        between(N2, InputLen, N3),
    
    
        \+ N1 = N2,                 % can't pick the same thing more than once.
        \+ N2 = N3,
    
        nth1(N1, RInput, A, _),
        nth1(N2, RInput, B, _),
        nth1(N3, RInput, C, _),
    
        sum_list([A,B,C], Goal).
    

    someone helped me to reach this to this code but it gives me singleton variables:[Input,Items], it didnt work

    The warning is because the code never looks at the numbers in the Input list. Without doing that, how could it ever work?

    although iam not quite sure if this is a greedy algorithm

    is it taking the biggest things first? I don't think permutation will do that.