Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: slice a list from the first non-zero element

Tags:

list

scala

Suppose I have a list filled with zeroes

val a = List(0,0,0,0,2,4,0,6,0,7)

I want to slice away the zeroes preceding the first non-zero element and also return the index where the 1st non-zero element is present. Foe the above case I want an output:

output = List(2,4,0,6,0,7)
idx = 4

How do I do it?

like image 468
ni_i_ru_sama Avatar asked Dec 05 '22 08:12

ni_i_ru_sama


1 Answers

First, you can use zipWithIndex to conveniently pair each element with its index. Then use dropWhile to return all of the preceding zero elements. From there, you'll have all of the remaining elements paired with their indices from the original List. You can unzip them. Since this may result in an empty list, the index you're looking for should be optional.

scala> val (remaining, indices) = a.zipWithIndex.dropWhile { case (a, i) => a == 0 }.unzip
remaining: List[Int] = List(2, 4, 0, 6, 0, 7) // <--- The list you want
indices: List[Int] = List(4, 5, 6, 7, 8, 9)

scala> val index = indices.headOption
index: Option[Int] = Some(4) // <--- the index of the first non-zero element
like image 106
Michael Zajac Avatar answered Dec 21 '22 14:12

Michael Zajac