簡體   English   中英

Prolog 如何在列表中寫一個謂詞和 3 個最大值?

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

如何在列表中寫一個謂詞和 3 個最大值? 最大 3(L,X)

例子:

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

作為起點:

% 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).

用法:

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

用了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.

列表中取A ,余數中取B ,余數中C ,必須A>=B>=C,且余數中不能有大於C的成員Q ,將它們相加。

這效率不高; brebs 的建議:

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

更整潔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM