Issue
Can someone please tell me how to find the mode of a list in Prolog?
I have tried this:
count_elt([], _, 0) :- !.
count_elt([H|T], H, P) :-
count_elt(T, H, P1),
P is P1 + 1, !.
count_elt([_|T], E, P) :- count_elt(T, E, P).
listMode([], 0) :- !.
listMode([_], 1) :- !.
listMode([H1|[H2|T]], M) :-
count_elt([H1|[H2|T]], H1, C),
listMode([H2|T], C1),
C > C1,
M is C, !.
listMode([_|[H2|T]], M) :- listMode([H2|T], M).
which only returns the maximum occurrences in the list. But I need to return the element which has the maximum occurrence (The most frequent value in the list).
Solution
Hope you already got number of suggestions. Here this is working code for you.
count_elt([],_,0):-!.
count_elt([H|T],H,C):-count_elt(T,H,C1),C is C1+1,!.
count_elt([_|T],E,C):-count_elt(T,E,C).
listMode([],0) :- !.
listMode([_],1) :- !.
listMode([H1|[H2|T]], M) :-count_elt([H1|[H2|T]],H1,C),listMode([H2|T],C1),C > C1,M is C,!.
listMode([_|[H2|T]],M) :- listMode([H2|T],M).
get_mode([H|T],M):-listMode([H|T],K),count_elt([H|T],M,K).
Answered By - Madusanka Answer Checked By - Robin (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.