user1050325
user1050325

Reputation: 1272

identify sequence of numbers in Scala

I was wondering what would be the logic to identify from a list of numbers a pattern of consecutive numbers and max of that in Scala. For example, if

val x = List(1,2,3,8,15,26)

Then the output of the function should be

val y = List(3,8,15,26) where 3 is the max of 1,2,3 which is a sequence of consecutive numbers. 8,15,26 are not consecutive and hence those numbers are unaltered.

The position does not matter, meaning, I can sort the list and then identify the sequences.

How to approach this problem?

Upvotes: 1

Views: 453

Answers (1)

jwvh
jwvh

Reputation: 51271

After x is sorted you could do something like this.

(x :+ x.last).sliding(2).filter(p => p(0) != p(1)-1).map(_(0)).toList

Upvotes: 4

Related Questions