Reputation: 2510
Given an input sequence:
Array[Int] = Array(0, 1, 0, 2, 1, 0)
I want a list that gives me indexes of each entry times, the number of times for each entry in the sequence. The output here would be:
Array[Int] = Array(1, 3, 3, 4)
There is one instance of index 1, two instances of index 3, one instance of index 4. How can write a function to do this in scala?
Here is one attempt, but I
val func1 = (cnt: Int, idx: Int) => Array.fill(cnt)(idx)
countarray.zipWithIndex.map(func1)
func1: (Int, Int) => Array[Int] = <function2>
<console>:132: error: type mismatch;
found : (Int, Int) => Array[Int]
required: ((Int, Int)) => ?
seq_of_vectors.map(_.numNonzeros).zipWithIndex.map(func1)
Upvotes: 0
Views: 68
Reputation: 51271
You're quite close.
arr.zipWithIndex.flatMap{case (rep,idx) => Array.fill(rep)(idx)}
Use flatMap()
so that all the intermediate Array
s will be flattened into one Array
result.
Upvotes: 4