HungryCoder
HungryCoder

Reputation: 1129

Prolog simple sort

In Prolog, what I have now is,

:-dynamic listofPeople/2.
listofPeople(Mark,Name).

which basically contains the mark for each student.

I want to print the best 3 marks.

To do that I believe I have to do sorting. If I do sorting, I will lose the order of the name of the student.

As you can understand by default, what I want is sort only the marks and sort the names according to the marks as well.

Please help. Code snippets appreciated.

Upvotes: 0

Views: 186

Answers (1)

Alexander Serebrenik
Alexander Serebrenik

Reputation: 3577

You can start by creating a list of key-value pairs, sort it and print the top 3 grades.

go(G1,G2,G3) :- findall(Grade-Name, listofPeople(Grade,Name), List), 
                 keysort(List, [G1-_,G2-_,G3-_|SortedList]).

The predicate fails if you have less than three grades.

If in addition to grades you want to have names:

go(N1-G1,N2-G2,N3-G3) :- findall(Grade-Name, listofPeople(Grade,Name), List), 
                 keysort(List, [G1-N1,G2-N2,G3-N3|SortedList]).

Upvotes: 1

Related Questions