Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Almost works!

Status
Not open for further replies.

WiseMonk

Programmer
Dec 4, 2010
2
LT
Hi,
I'm trying to make this program work :)
we have a list common([a,d,a,c,d,a,b],R). and R=a the most common letter!
so this is how we probably should find it:

common([X|T],E):- last(T,E),%find the last element (b)
sum([X|T],E,M1),%find how many times that element repeats itself ,count b M1=1
sum([X|T],X,M2),%compare first element of the list with the rest get count(lets say a repeats itself 3 times [a,a,b,a] but sum only works with the first element of the list and leaves the others)
M2>M1->(M1 is M2 ; change(X,E)); %because a count is 3 we change E to a! and change M1 value to M2 value(something is not right here :/)
common(T,E).
common([_|T],E).

last([Elem], Elem).%last list elem
last([_|Tail], Elem) :- last(Tail, Elem).

change(X,E):-append([],X,E).

sum([X|T],E,M1):- X = E,sum(T,E,C),M1 is 1+C.% count how many times repeats itself
sum([X|T],E,M1):- X \== E,sum(T,E,M1).
sum([],E,0).


 
I think you should travel the initial list to obtain a list of tuple (NbLetter, Letter) eg from [a,d,a,c,d,a,b] obtain [(1,b), (1,c), (2,d), (3,a)], then sort the list in reverse order to obtain [3,a), (2,d), (1,b),(1,b)] and take the head of the list.
 
Yes you are absolutely right ! but before i do anything i should sort the list sort/2 and use @< @=> because we compare letters :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top