SHARE
TWEET

Ex 2.2

a guest Sep 15th, 2019 77 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package dk.itu.BIDMT.F19.P1.Part2
  2.  
  3. object SortingLists {
  4.  
  5.   /**
  6.     *
  7.     * Sort the input listOfLists in an ascending order  based on the length of each sub-list and return the sorted list
  8.     *
  9.     * For example, the sorting of the list: List(List('a', 'b', 'c'), List('d', 'e'), List('f', 'g', 'h'), List('d', 'e'), List('i', 'j', 'k', 'l'), List('m', 'n'), List('o'))
  10.     * should be: List(List(o), List(d, e), List(d, e), List(m, n), List(a, b, c), List(f, g, h), List(i, j, k, l))
  11.     */
  12.   def sortListLength(listOfLists: List[List[Char]]): List[List[Char]]  =
  13.     listOfLists sortBy {_.length}
  14.  
  15.   /**
  16.     * Sort the sublists of the input list in an ascending order  based on the frequency of the lengths of these sublists.
  17.     *
  18.     * For example, the sorting of the list: List(List('a', 'b', 'c'), List('d', 'e'), List('f', 'g', 'h'), List('d', 'e'), List('i', 'j', 'k', 'l'), List('m', 'n'), List('o'))
  19.     * should be: List(List(i, j, k, l), List(o), List(a, b, c), List(f, g, h), List(d, e), List(d, e), List(m, n))
  20.     *
  21.     * since:
  22.     *   freq of sub-lists of length 4 is 1
  23.     *   freq of sub-lists of length 1 is 1
  24.     *   freq of sub-lists of length 3 is 2
  25.     *   freq of sub-lists of length 2 is 3
  26.     *
  27.     *  Hint:
  28.     *  Follow the following steps:
  29.     *   - pair each sub-list with its length
  30.     *   - find the freq of each length, you can use groupby for that
  31.     *   - sort the groups according to the number of sub-lists in each group
  32.     *   - generate the final sorted list
  33.     */
  34.   def sortListFreq(listOfLists: List[List[Char]]): List[List[Char]] = {
  35.     val pairs = listOfLists.map(e => (e.length, e))
  36.     val length_freq = pairs.groupBy(_._1).mapValues(_.map(_._2))
  37.     length_freq.values.toList.sortBy(_.length).flatten
  38. }
  39.  
  40.  
  41.   def main(args: Array[String]):Unit = {
  42.     val ls = List(List('a', 'b', 'c'), List('d', 'e'), List('f', 'g', 'h'), List('d', 'e'), List('i', 'j', 'k', 'l'), List('m', 'n'), List('o'))
  43.     println("Sorted list according to lengths of sublists: "+ sortListLength(ls))
  44.     println("Sorted list according to frequency of lengths of sublists: "+ sortListFreq(ls))
  45.   }
  46. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top