testing2/danube.scala
changeset 266 ca48ac1d3c3e
parent 249 1997cfcd6334
child 284 9a04eb6a2291
equal deleted inserted replaced
265:59779ce322a6 266:ca48ac1d3c3e
   122 
   122 
   123 
   123 
   124 // (5) Implement a suggestions function which takes a rating
   124 // (5) Implement a suggestions function which takes a rating
   125 // map and a movie_name as arguments. It calculates all the recommended
   125 // map and a movie_name as arguments. It calculates all the recommended
   126 // movies sorted according to the most frequently suggested movie(s) first.
   126 // movies sorted according to the most frequently suggested movie(s) first.
       
   127 
       
   128 // needed in Scala 2.13.
       
   129  
       
   130 def mapValues[S, T, R](m: Map[S, T], f: T => R) =
       
   131   m.map { case (x, y) => (x, f(y)) }
       
   132 
   127 def suggestions(recs: Map[String, List[String]], 
   133 def suggestions(recs: Map[String, List[String]], 
   128                     mov_name: String) : List[String] = {
   134                     mov_name: String) : List[String] = {
   129   val favs = favourites(recs, mov_name).flatten
   135   val favs = favourites(recs, mov_name).flatten
   130   val favs_counted = favs.groupBy(identity).mapValues(_.size).toList
   136   val favs_counted = mapValues(favs.groupBy(identity), (v:List[String]) => v.size).toList
   131   val favs_sorted = favs_counted.sortBy(_._2).reverse
   137   val favs_sorted = favs_counted.sortBy(_._2).reverse
   132   favs_sorted.map(_._1)
   138   favs_sorted.map(_._1)
   133 }
   139 }
       
   140 
       
   141 // check
       
   142 // groupMap is equivalent to groupBy(key).mapValues(_.map(f))
   134 
   143 
   135 // test cases
   144 // test cases
   136 
   145 
   137 //suggestions(ratings_map, "912")
   146 //suggestions(ratings_map, "912")
   138 //suggestions(ratings_map, "912").length  
   147 //suggestions(ratings_map, "912").length