tags:

views:

144

answers:

2

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?

+3  A: 
val arr = Array(1,2,4,3,3,4,5)
def index(sub: Int, f: Int => Boolean): Int = {
  var i = arr.length-sub                       
  while (f(i)) i -= 1                          
  i                                            
}                                              
val largest = index(2, i => arr(i) > arr(i+1))
val smallest = index(1, i => arr(largest) > arr(i))
Daniel
Thanks! That works fine.
Antoras
+1  A: 
val arr = Array(1,2,4,3,3,4,5)
arr: Array[Int] = Array(1, 2, 4, 3, 3, 4, 5)

scala> arr.zipWithIndex.max(Ordering.by((x: (Int, Int)) => x._1))._2
res0: Int = 6

scala> arr.zipWithIndex.min(Ordering.by((x: (Int, Int)) => x._1))._2
res1: Int = 0

or

scala> val pairOrdering = Ordering.by((x: (Int, Int)) => x._1)
pairOrdering: scala.math.Ordering[(Int, Int)] = scala.math.Ordering$$anon$4@145ad3d

scala> arr.zipWithIndex.max(pairOrdering)._2
res2: Int = 6

scala> arr.zipWithIndex.min(pairOrdering)._2
res3: Int = 0
Randall Schulz
Nice answer. But it doesn't work absolutely correct for me. With each call of the method I want to generate the next permutation of number. With your code the numbers are correct, but they aren't sorted.
Antoras
I don't know what you mean by "permutation of number." Are you trying to generate permutations some *distinct* numbers? Using a non-recursive, stateless algorithm? If so, I would (and have) avoid the functional approach and just use explicit indexes to find the transition points within the array.
Randall Schulz