0

I need to count occurrences of element in list.

List looks like this: List[(String, String, Int)] - list of (String, String, Int) tuples.

Example:

List(("Gregor", "Math", 6), ("Mark", "Math", 33), 
     ("Gregor", "IT", 44),  ("Jane", "Math", 3), 
     ("Mark", "Geography", 44), ("Gregor", "sdf", 32))

And I need to return list of pairs (name, occurrences in list) For this example it should be

List(("Gregor", 3), ("Mark", 2), ("Jane", 1))

I tried with map and foldLeft but i dont have idea how can I do that

Cœur
  • 37,241
  • 25
  • 195
  • 267
akcza
  • 43
  • 1
  • 1
  • 6

3 Answers3

3

You could do this with only using foldLeft:

val t = List(("Gregor", "Math", 6), ("Mark", "Mat", 33), 
    ("Gregor", "IT", 44), ("Jane", "Math", 3), ("Mark", "Geography", 44), 
    ("Gregor", "sdf", 32))

val res = t.foldLeft(Map[String, Int]()) { case(m, (n, _, _)) => 
    m + (n -> (m.getOrElse(n, 0) + 1)) 
}.toList
Johan S
  • 3,531
  • 6
  • 35
  • 63
  • I guess you have to use the toList right? Atleast otherwise you will have a truly horrible complexity. – Johan S Nov 22 '14 at 20:52
0
users.groupBy(u => u._1).map(u => (u._1, u._2.length)).toList
Dmitri
  • 2,451
  • 6
  • 35
  • 55
  • `groupBy` can't be used, this was my first thought too. – Johan S Nov 22 '14 at 20:45
  • Hm. Strange constraint, but ok, I'll give it a thought. Any other constraints? – Dmitri Nov 22 '14 at 20:46
  • Check the comments on the question, he did say that we are only allowed to use `foldLeft`, `foldRight`, `map` and `filter`. It's obviously a homework question but fun nonetheless. – Johan S Nov 22 '14 at 20:55
0
scala> val list = List(("Gregor", "Math", 6), ("Mark", "Mat", 33), ("Gregor", "IT", 44), ("Jane", "Math", 3), ("Mark", "Geography", 44), ("Gregor", "sdf", 32))
list: List[(String, String, Int)] = List((Gregor,Math,6), (Mark,Mat,33), (Gregor,IT,44), (Jane,Math,3), (Mark,Geography,44), (Gregor,sdf,32))

scala> val res = list.groupBy(_._1) map { case (k, xs) => k -> xs.size } toList
res: List[(String, Int)] = List((Gregor,3), (Jane,1), (Mark,2))
hellraiser
  • 1,451
  • 12
  • 19