Suppose we have a binary string such as 10010010.
All I want is a function returning indices of 1s 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
filterand thenmapto get the index :Note: I'm using
withFilterand notfilterto avoid creating a temporary collection.Or you can use
collect, which applies a partial function on the elements over which it is defined: