user3813755
user3813755

Reputation: 13

Prolog - Get maximum calculation of list elements

I am working with PROLOG for 2 weeks now and I can't manage to solve the following:

Define u/3, that identifies the best possible arithmetic term and its resulting maximum value out of a list of numbers. Example:

    ?- u([18,0.25,3,4],Max,Term).
    Max = 300.0,
    Term = (18/0.25- -3)*4 ;
    false.

I may use this to solve the problem:

    split(List,Left,Right) :-
       append(Left,Right,List),
       Left = [_|_],
       Right = [_|_].

    binterm(T1,T2,T1+T2).
    binterm(T1,T2,T1-T2).
    binterm(T1,T2,T1*T2).
    binterm(T1,T2,T1/T2) :- T2 =\= 0.

    term([E],E).
    term(List,Term) :-
       split(List,Left,Right),
       term(Left,LeftTerm),
       term(Right,RightTerm),
       binterm(LeftTerm,RightTerm,Term).

term/2 does:

    ?- term([2,3,4],R).
    R = 2+ (3+4) ;
    R = 2- (3+4) ;
    R = 2* (3+4) ;
    R = 2/ (3+4) ;
    R = 2+ (3-4) ;
    R = 2- (3-4) ;
    R = 2* (3-4) ;
    R = 2/ (3-4) ;
    R = 2+3*4 ;
    R = 2-3*4 ;
    R = 2* (3*4) ;
    R = 2/ (3*4) ;
    R = 2+3/4 ;
    R = 2-3/4 ;
    R = 2* (3/4) ;
    R = 2+3+4 ;
    R = 2+3-4 ;
    R = (2+3)*4 ;
    R = (2+3)/4 ;
    R = 2-3+4 ;
    R = 2-3-4 ;
    R = (2-3)*4 ;
    R = (2-3)/4 ;
    R = 2*3+4 ;
    R = 2*3-4 ;
    R = 2*3*4 ;
    R = 2*3/4 ;
    R = 2/3+4 ;
    R = 2/3-4 ;
    R = 2/3*4 ;
    R = 2/3/4 ;
    false.

Thanks in advance!

Upvotes: 1

Views: 112

Answers (1)

CapelliC
CapelliC

Reputation: 60034

a very simple - and very inefficient - way could be

u(Ns, Max, TMax) :-
  term(Ns, TMax), Max is TMax, \+ ( term(Ns, Try), Try > Max ).

yields

?- u([18,0.25,3,4],Max,Term).
Max = 864.0,
Term = 18/ (0.25/ (3*4)) .

Upvotes: 1

Related Questions