Reputation: 645
I am looking for an elegant solution for finding the position of an element in a seq of sequences. e.g.
def findChar(c: Char, levelVector: Vector[Vector[Char]]): (x,y) = {
val x = levelVector.indexWhere(vect=>vect.indexOf(c) != -1)
(x,levelVector(x).indexOf(c))
}
this works fine, but somehow I have a gut feeling, there should be a better elegant solution , some scala or FP construct which i am not able to recall [long years of imperative programming can do this kind of damage :) ]. which lets me do the work of
vect.indexOf(c)
only once. I have explored other constructs like flattening or for comprehension, but does not seems elegant or simple. we can assume that vector is non-empty and element is unique.
any suggestions appreciated.
Upvotes: 2
Views: 157
Reputation: 2088
Neither elegant nor succinct, but a solution nevertheless, one that I hammered out because I forced myself to do it using a for comprehension:
def findChar(c: Char, levelVector: Vector[Vector[Char]]): (Int, Int) = {
val y = for (
i <- 0 to levelVector.view.length - 1;
v = levelVector.view(i);
j = v.indexOf(c) if j != -1
) yield (i, j)
y.take(1)(0)
}
I might delete this answer soon :-)
Upvotes: 0
Reputation: 170745
Something like this should work
def findChar(c: Char, levelVector: Vector[Vector[Char]]) = {
// view is to ensure indices are only calculated up to the element you need
val vec1 = levelVector.view.map(_.indexOf(c))
val x = vec1.indexWhere(_ != -1)
if (x != -1)
Some((x, vec1(x)))
else
None // or (-1, -1) if you prefer
}
Upvotes: 2