Hi,
I have this code:
val arr: Array[Int] = ...
val largestIndex = {
var i = arr.length-2
while (arr(i) > arr(i+1)) i -= 1
i
}
val smallestIndex = {
var k = arr.length-1
while (arr(largestIndex) > arr(k)) k -= 1
k
}
But there is to much code duplication. I tried to rewrite this with closures but I failed. I tried something like this:
def index(sub: Int, f: => Boolean): Int = {
var i = arr.length-sub
while (f) i -= 1
i
}
val largest = index(2, i => arr(i) > arr(i+1))
val smallest = index(1, i => arr(largest) > arr(i))
The problem is that i can't use parameter i of the method index() in the closure. Is there a way to avoid this problem?