Wednesday, May 16, 2012

sorting according to a custom comparator

I've got a map looking like this:



user> (frequencies "aaabccddddee")
{\a 3, \b 1, \c 2, \d 4, \e 2}


And I'd like to have a function that would sort the key/value pairs according to the order each character is appearing in a string I'd pass as an argument.



Something like this:



user> (somesort "defgcab" (frequencies "aaabccddddee"))
[[\d 4] [\e 2] [\c 2] [\a 3] [\b 1]]


(in the example above 'f' and 'g' do not appear in the map and they're hence ignored. It is guaranteed that the string -- "defgcab" in this example -- shall contain every character/key in the map)



The resulting collection doesn't matter much as long as it is sorted.



I've tried several things but cannot find a way to make this work.





No comments:

Post a Comment