简体   繁体   English

从事实列表中找到最大的序言

[英]prolog finding max from a list of facts

Hi sorry I'm really new to Prolog. 嗨,抱歉,我真的是Prolog的新手。 Say I have a list of facts say 6 facts the first column of numbers represents the persons ID, and the second column represents the number of wins a person has. 假设我有一个事实列表,说6个事实,第一列数字代表人员ID,第二列代表一个人的获胜次数。 If I want to find the person with the most wins how would I go about doing this? 如果我想找到获胜最多的人,我将如何去做?

wins(1, 22).
wins(2, 24).
wins(3, 23).
wins(4, 20).
wins(5, 21).
wins(6, 19).

something like that? 这样的东西? lol to be honest, I don't really know what I'm doing 老实说,我真的不知道我在做什么

X = wins(_, Xs) 
Y = wins(_, Ys)
most wins(X) :- Xs > Ys  

There is more than a way to obtain that info. 获得该信息的方法不止一种。

most_wins(Id) :-
    wins(Id, W), \+ (wins(_, W1), W1 > W).

or, if your Prolog has library( aggregate ) :- 或者,如果您的Prolog具有library( aggregate ):

most_wins(Id) :-
    aggregate(max(W, Id), wins(Id, W), max(_, Id)).

or you could use setof /3 或者您可以使用setof / 3

most_wins(Id) :-
    setof(N-Id, W^(wins(Id, W), N is -W), [_-Id|_]).

There are obvious speed/memory trade-offs: the first way it's memory efficient, O(1), but time complexity is O(N^2), because it scans 2 times the set of candidates. 有明显的速度/内存折衷:第一种方法是提高内存效率,即O(1),但是时间复杂度为O(N ^ 2),因为它扫描的是候选集的2倍。 Second and third are (I think) practically equivalent, under current implementation in SWI-prolog, both build the list of candidates (then are O(N) in space) and then select the element - O(N log N) in time. 第二个和第三个(在我看来)实际上是等效的,在SWI-prolog中的当前实现下,都建立候选列表(然后是空间中的O(N)),然后及时选择元素-O(N log N)。

Go with the first if the candidates are facts . 如果候选人是事实 ,则首先选择。

edit Yet another way, the better from the efficiency viewpoint, make use of non-backtrackable assignment. 编辑从效率的角度来看,更好的方法是利用不可回溯的分配。 Just scan the candidates, keeping the max on the go. 只需扫描候选人,即可随时随地保持最高水平。 Plain Prolog will require assert/retract to perform such task, making it rather inefficient. Plain Prolog将需要断言/收回来执行此类任务,从而使其效率低下。 But many Prologs have more efficient ways to store 'global' variables... 但是许多Prologs都有更有效的方式来存储“全局”变量...

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

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