Reputation: 383
I'm writing this function in order to identify the first missing element from the array. I want to return the missing element but I'm getting a Unit
I can't identify what am I missing
def missingElement(a : Array[Int]) : Int = {
val result =for (i <- 1 to a.length) {
if(! a.contains(i)) {
i
}
}
result
}
Upvotes: 0
Views: 92
Reputation: 27356
"identify the first" is a find
operation, so the code might look like this:
def missingElement(a: Array[Int]): Option[Int] =
a.indices.find(i => !a.contains(i+1))
This returns an Option
because there might not be a missing element, in which case it will return None
, otherwise it will return Some(n)
.
Upvotes: 3