gpt4 book ai didi

list - Prolog 列表中的重复元素

转载 作者:行者123 更新时间:2023-12-04 00:03:09 25 4
gpt4 key购买 nike

如果两个元素重复相同次数,我想找到一种方法来查找列表中重复次数最多的元素。我希望谓词是一个包含这两个元素的列表。我该怎么做?

示例查询和预期答案:

?- maxRepeated([1,3,3,4,2,2],X).
X = [3,2].

% common case: there is one element that is the most repeated
?- maxRepeated([1,3,3,3,3,4,2,2],X).
X = [3].

% all elements repeat the same number of times
?- maxRepeated([1,3,4,2],X).
X = [1,3,4,2].

我对较少重复的元素有同样的问题。

最佳答案

谓词mostcommonitem<b><i>s</i></b>_in/2 (将在这个答案中呈现)与 mostcommonitem_in/2 , defined in one of my previous answers .

下面我们使用 list_counts/2 , Prolog lambdas , foldl/4 , tchoose/3 , 和 (=)/3 :

:- use_module(library(lambda)).

mostcommonitems_in(Ms,Xs) :-
list_counts(Xs,Cs),
foldl(\ (_-N)^M0^M1^(M1 is max(M0,N)),Cs,0,M),
tchoose(\ (E-N)^E^(N=M), Cs,Ms).

让我们运行一些查询!

首先,OP给出的三个查询:

?- mostcommonitems_in(Xs,[1,3,3,4,2,2]).Xs = [3,2].?- mostcommonitems_in(Xs,[1,3,3,3,3,4,2,2]).Xs = [3].?- mostcommonitems_in(Xs,[1,3,4,2]).Xs = [1,3,4,2].

Alright! Some more ground queries---hat tip to @lurker and @rpax:

?- mostcommonitems_in(Xs,[1,3,2,1,3,3,1,4,1]).Xs = [1].?- mostcommonitems_in(Xs,[1,3,3,4,3,2]).Xs = [3].?- mostcommonitems_in(Xs,[1,2,3,4,5,6]).Xs = [1,2,3,4,5,6].?- mostcommonitems_in(Xs,[1,3,3,4,2,3,2,2]).Xs = [3,2].

OK! How about three items each of which occurs exactly three times in the list?

?- mostcommonitems_in(Xs,[a,b,c,a,b,c,a,b,c,x,d,e]).
Xs = [a,b,c]. % works as expected

下面的更一般查询怎么样?

?- mostcommonitems_in(Xs,[A,B,C]).
Xs = [C] , A=B , B=C
; Xs = [B] , A=B , dif(B,C)
; Xs = [C] , A=C , dif(B,C)
; Xs = [C] , dif(A,C), B=C
; Xs = [A,B,C], dif(A,B), dif(A,C), dif(B,C).

上面的查询打破了几乎所有不纯的代码...我们的 Prolog 代码是的,所以我们可以开始了!

关于list - Prolog 列表中的重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23766536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com