简体   繁体   English

Prolog 如何在列表中写一个谓词和 3 个最大值?

[英]Prolog How to write a predicate sum 3 max values in list?

How to write a predicate sum 3 max values in list?如何在列表中写一个谓词和 3 个最大值? max3(L,X)最大 3(L,X)

Example:例子:

max3([1,7,9,3,5],X).
X = 21.

As a starting point:作为起点:

% Can potentially change order of the list in Rest
list_max_rest([H|T], Max, Rest) :-
    list_max_rest_(T, H, Max, Rest).
    
list_max_rest_([], Max, Max, []).
list_max_rest_([H|T], P, Max, [P|Rest]) :-
    H @> P,
    !,
    list_max_rest_(T, H, Max, Rest).
list_max_rest_([H|T], P, Max, [H|Rest]) :-
    list_max_rest_(T, P, Max, Rest).

Usage:用法:

?- list_max_rest([2,1,200,9], Max, Res).
Max = 200,
Res = [1, 2, 9].

Use that 3 times...用了3次...

max3(Ls, X) :-
    select(A, Ls,  Ls2),
    select(B, Ls2, Ls3),
    select(C, Ls3, Ls4),
    A >= B,
    B >= C,
    \+ (member(Q, Ls4), Q > C),
    X is A+B+C.

Take A from the list, B from the remainder, C from that remainder, they must be A>=B>=C, and there must not be a member Q left in the remainder which is bigger than C. Add those up.列表中取A ,余数中取B ,余数中C ,必须A>=B>=C,且余数中不能有大于C的成员Q ,将它们相加。

This is not efficient;这效率不高; brebs' suggestion of: brebs 的建议:

max3(Ls, X) :-
    sort(0, @>=, Ls, [A,B,C|_]),
    X is A+B+C.

is neater更整洁

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM