Prolog - 获取列表元素的最大计算

时间:2014-07-07 19:44:25

标签: prolog

我正在与PROLOG合作2周,我无法解决以下问题:

定义u / 3,用于标识数字列表中最佳的算术项及其最终的最大值。 例如:

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

我可以用它来解决问题:

    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确实:

    ?- 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.

提前致谢!

1 个答案:

答案 0 :(得分:1)

非常简单 - 效率很低 - 可能

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

产量

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