You can try sorting your list and then use foldLeft. Basically something like this
def sort = { val l = List(2,3,1,6,10,7,11,12,14) val dist = 1 l.sorted.foldLeft(List(List.empty[Int]))((list, n) => { val last = list.head last match { case h::q if Math.abs(last.head-n) > dist=> List(n) :: list case _ => (n :: last ) :: list.tail } } ) }
The result looks fine, but vice versa. If necessary, call "reverse", if necessary, in the lists. the code becomes
val l = List(2,3,1,6,10,7,11,12,14) val dist = 1 val res = l.sorted.foldLeft(List(List.empty[Int]))((list, n) => { val last = list.head last match { case h::q if Math.abs(last.head-n) > dist=> List(n) :: (last.reverse :: list.tail) case _ => (n :: last ) :: list.tail } } ).reverse
source share