//First Part: Separates the list into ordered pairs with tail - head == 1
val ls = List(1,2,3,7,8,10,13,14)
val lb: ListBuffer[List[Int]] = new ListBuffer[List[Int]]()
for (List(left,right) <- ls.sorted.sliding(2)) {
if (right - left == 1) {
lb += List(left, right)
}else {
if(!lb.flatten.toList.contains(left)) lb += List(left)
}
}
println(lb.toList)
//Second Part: Merges ordered pairs (x1, y1) and (x2, y2) when y1 == y2
val finalLb: ListBuffer[List[Int]] = new ListBuffer[List[Int]]()
for (List(left,right) <- lb.toList.sliding(2)) {
if(left.tail.contains(right.head)) {
finalLb += (left ++ right).distinct
}else{
finalLb += right
}
}
println(finalLb.toList)
Выходы
First Part: List(List(1, 2), List(2, 3), List(7, 8), List(10), List(13, 14))
Second Part: List(List(1, 2, 3), List(7, 8), List(10), List(13, 14))