elm
elm

Reputation: 20415

Scala grouping a collection by a finite sequence of values

For

val xs = (1 to 9).toArray

we can group for instance every two consecutive items like this,

xs.grouped(2)

Yet, given a finite sequence of values, namely for instance

val gr = Seq(3,2,1)

how to group xs based in gr so that

xs.grouped(gr)
res: Array(Array(1,2,3), Array(4,5), Array(6), Array(7,8,9))

Upvotes: 1

Views: 73

Answers (2)

Nyavro
Nyavro

Reputation: 8866

Please, consider the following solution:

def groupBySeq[T](arr:Array[T], gr:Seq[Int]) = {
  val r = gr.foldLeft((arr, List[Array[T]]())) {
    case ((rest, acc), item) => (rest.drop(item), rest.take(item)::acc)
  }
  (r._1::r._2).reverse
}

Upvotes: 2

Shadowlands
Shadowlands

Reputation: 15074

The following function generates the result you are looking for, although I suspect there may be a better way:

def grouped[T](what: Seq[T], by: Seq[Int]) = {

  def go(left: Seq[T], nextBy: Int, acc: List[Seq[T]]): List[Seq[T]] = (left.length, by(nextBy % by.length)) match {
    case (n, sz) if n <= sz => left :: acc
    case (n, sz) => go(left.drop(sz), nextBy+1, left.take(sz) :: acc)
  }

  go(what, 0, Nil).reverse
}

Upvotes: 1

Related Questions