I'm trying to find the most common list item common([b,a,a,a,c,d,b,f,s,f,s,f,s,f,s,f,f],R) so the result should be R=f, I was thinking if we take the list , go to the end of the list take el=b ,num1=1 then go back to the beginning and compare if b=b ,num1=num1+1 else a!=b then if num2=num2+1 , num1>num2 recursion else el=a or something like this, but i had some difficulty transforming it into Prolog.
insert_sort sorts the list , but for some interesting reason if i use las(X,Y)
(I override the original last/2
) I get 4-a if I use last(X,Y)
i get just a...
most_common([X|Y],J):-
insert_sort([X|Y],[R|Rs]),
count_runs([R|Rs],G),
las(G,J).
las([N-Y],Y).
las([_|T],Y):- las(T,Y).
las([_|Tail], Y) :- las(Tail, Y).
insert_sort(List,Sorted):-
i_sort(List,[],Sorted).
i_sort([],Acc,Acc).
i_sort([H|T],Acc,Sorted):-
insert(H,Acc,NAcc),
i_sort(T,NAcc,Sorted).
insert(X,[],[X]).
insert(X,[Y|T],[Y|NT]):- X @> Y, insert(X,T,NT).
insert(X,[Y|T],[X,Y|T]):- X @=< Y.
Preserve logical-purity by using
list_counts/2
for definingmostcommonitem_in/2
as follows:Let's run a query!
But, is it still monotone?
Got speed? (compared to the pure answer I showed in my previous answer to this question)
Based on Prolog lambdas, we use the meta-predicates
tcount/3
andreduce/3
, as well as the reified term equality predicate(=)/3
:Sample query:
Note that this is monotone (unlike it's earlier quick-hack version). Look!
I could give you a high-level answer: You could sort the list and then it's relatively easy to count the items, one after another, and update what so far is the most common item.
This looks like homework, so I'm not going to give you a full answer, but will suggest how you could solve it in one particular way, which isn't necessarily the best way:
Sort the list into sorted order (by standard order of terms if this is good enough): look at
sort/2
routines. e.g.,[b,a,a,a,c,d,b]
becomes[a,a,a,b,b,c,d]
.Take the sorted list and count the size of 'runs', perhaps to convert
[a,a,a,b,b,c,d]
into[3-a,2-b,1-c,1-d]
(where-
/2 is simply another term). e.g., consider the following code:keysort/2
to order the terms by the value of their keys (i.e., the numbers which are the counts, turning[3-a,2-b,1-c,1-d]
into[1-c,1-d,2-b,3-a]
). Then, the most-occurring elements of the list are the values at the end of the list with the same key value (i.e., here, this is thea
in the last term3-a
). In general, they may be more than one element that occurs the most (equally with another).Good luck.