Reputation: 31
Is there a way to sort two lists relative to each other.
Suppose I have two lists as follows:
Age = [14,12,17,15].
Name = ["Frank", "Micheal","Paul","Alex"].
Frank's age is 14 while Alex's age is 15.
I want to sort the Age list and also want the Name list to change its order relative to Age list.
so, basically what I want to see in the result is:
Age = [12, 14, 15, 17]
Name = ["Micheal", "Frank", "Alex", "Paul"].
any suggestions?
Upvotes: 1
Views: 46
Reputation: 58294
You can map them to a single associative list, sort, then unmap:
associate(X, Y, X-Y).
sort_age_name(Ages, Names, SortedAges, SortedNames) :-
maplist(associate, Ages, Names, AgesNames),
msort(AgesNames, SortedAgesNames),
maplist(associate, SortedAges, SortedNames, SortedAgesNames).
The first maplist
call associates the two lists with a single list where each element is Age-Name
, the age with the associated name. You can think of it as "zipping" the two lists together.
The msort
call sorts the list of age-name associations by age.
The second maplist
call associates two individual lists with the sorted associative list. It basically "unzips" the associative list into component lists.
Since you have that kind of association between the two lists, it would make sense if they were a single associative list to start with. Having them separate is more cumbersome.
Upvotes: 2