My Avatar

Shilong ZHAO

[s 99] p09 pack consecutive duplicates

2020-06-23 00:00:00 +0200

In case you have any questions or suggestions, you can leave comments HERE . Thanks!

Pack consecutive duplicates of list elements into sublists.

If a list contains repeated elements they should be placed in separate sublists. Example:

scala> pack(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e))
res0: List[List[Symbol]] = List(List('a, 'a, 'a, 'a), List('b), List('c, 'c), List('a, 'a), List('d), List('e, 'e, 'e, 'e))
def pack(list: List[Symbol]): List[List[Symbol]] = pack(List[List[Symbol]](), List[Symbol](), list)

def pack(lists: List[List[Symbol]], list: List[Symbol], rem: List[Symbol]): List[List[Symbol]] = rem match {
    case Nil => lists :+ list
    case x::xs if (list.isEmpty || list.contains(x)) => pack(lists, list :+ x, xs)
    case _ => pack(lists :+ list, List(), rem)
pack(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e))