Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to split a list into groups by week in scala

Tags:

list

split

scala

case class Test(dayOfWeek:Int,b:Int=Random.nextInt)
val data=(3 to 100).map(_ % 7).map(Test(_))

how to split the data into groups, each group have one week's data, if a week is not complete, also have a group. So the group should be

Group 1: (3,4,5,6)   // the number here is the dayOfWeek
Group 2: (0,1,2,3,4,5,6)
Group 3: (0,1,2,3,4,5,6)
...
last Group:(0,1,2)
like image 827
Daniel Wu Avatar asked Feb 12 '23 10:02

Daniel Wu


1 Answers

Scala's collections are really powerful, this should do it in a couple of lines:

val (firstWeek, nextWeeks) = data.span(_.dayOfWeek != 0)
val weeks = (firstWeek :: nextWeeks.grouped(7).toList).dropWhile(_.isEmpty)

Look at the doc for span and grouped here.

println(weeks.zipWithIndex.map {
  case (week, i) => s"Group $i: (${week.map(_.dayOfWeek).mkString(",")})"
}.mkString("\n"))

outputs:

Group 0: (3,4,5,6)
Group 1: (0,1,2,3,4,5,6)
Group 2: (0,1,2,3,4,5,6)
[snip]
Group 12: (0,1,2,3,4,5,6)
Group 13: (0,1,2,3,4,5,6)
Group 14: (0,1,2)
like image 138
Utaal Avatar answered Feb 16 '23 03:02

Utaal