Suppose we have a binary string such as 10010010
.
All I want is a function returning indices of 1
s for that string:
indicesOfOnes("10010010") -> List(0, 3, 6)
indicesOfOnes("0") -> List()
And what I implemented is:
def indicesOfOnes(bs: String): List[Int] = {
val lb = ListBuffer[Int]()
bs.zipWithIndex.foreach { case (v, i) =>
if (v == '1') {
lb += i
}
}
lb.toList
}
This works, but I think there're much better (more functional) ways to do this job. Any advices would be appreciated.
You can use a
filter
and thenmap
to get the index :Note: I'm using
withFilter
and notfilter
to avoid creating a temporary collection.Or you can use
collect
, which applies a partial function on the elements over which it is defined: