Abdoul Cisse
Abdoul Cisse

Reputation: 33

Is there a nice way in Scala to convert a List of numbers into a List of ranges?

I haven't found so far a way to do the opposite operation of List.range:

Existent range function in Scala collections:

List.range(1, 4) = [1, 2, 3]

Looking for writing kind of toRanges function that could give me the following results:

List(1,3,4,5,7,8,9).toRanges() = [(1,1), (3,5), (7,9)]

I'm trying to see how's the functional way of achieving it

If you look into How to transform a list of numbers into a list of ranges of consecutive numbers The answer given is too large and imperative.

Thanks

Upvotes: 3

Views: 159

Answers (1)

Nyavro
Nyavro

Reputation: 8866

toRanges funciton may look like:

def toRanges(list:List[Int]) = list.foldLeft(List[(Int,Int)]()) {
  case (Nil, i) => (i,i)::Nil
  case ((a,b)::t, i) => if (b+1==i) (a, i)::t else (i,i)::(a,b)::t
}.reverse

Upvotes: 5

Related Questions