Hint for wk 6 homework (Anagrams)

350 views
Skip to first unread message

Robert Kohlenberger

unread,
Oct 26, 2012, 6:32:10 PM10/26/12
to scala-c...@googlegroups.com
In the Assignment Details, under Computing Occurrence Lists, the instructions suggest to implement method wordOccurrences by using the List groupBy method to generate a map.  The wordOccurrences parameter w is a Word (String), which is easily converted into a List of characters.  Calling method groupBy to group by element (Char) value gives a Map of key -> value pairs in which each key is a letter in the word, and the value is a List[Char], whose length is the count of that letter in the word.  This Map has all the information needed to produce the Occurrences result, which must be a List of pairs: List[(Char, Int)].  The remaining catch is the instruction that, "The list should be sorted by the characters in an ascending order."

At first I thought of implementing a merge sort algorithm described in a previous video.  But then I saw in Lecture 6.6, "Maps", a slide called "Sorted and GroupBy" which introduces the Map method "sortWith" that lets you define a "lt" (less than) function.  So I think we're free to use "sortWith" to sort Occurrences in the homework.

Hope this is useful.

Albert Lee

unread,
Oct 26, 2012, 9:05:04 PM10/26/12
to scala-c...@googlegroups.com
At first I thought of implementing a merge sort algorithm described in a previous video.  But then I saw in Lecture 6.6, "Maps", a slide called "Sorted and GroupBy" which introduces the Map method "sortWith" that lets you define a "lt" (less than) function.  So I think we're free to use "sortWith" to sort Occurrences in the homework.

Do you mean the List method sortWith? I don't think there's a sortWith method in the Map class.

In addition to sortWith, the List class also has a "sorted" method that can use a default ordering so you don't need specify a "lt" function.

- Albert

Reply all
Reply to author
Forward
0 new messages