Skip to content

Instantly share code, notes, and snippets.

@cb372
Created August 2, 2012 01:04
Show Gist options
  • Save cb372/3232116 to your computer and use it in GitHub Desktop.
Save cb372/3232116 to your computer and use it in GitHub Desktop.
def add1(arr: Array[Int], value: Int, n: Int): Array[Int] = {
n match {
case 0 => loop(arr, value, 0, 1, {_ < arr.length}, arr.length)
case m if m > 0 => loop(arr, value, 0, 1, {_ < arr.length}, m)
case m if m < 0 => loop(arr, value, arr.length - 1, -1, {_ > 0}, -m)
}
arr
}
private def loop(arr: Array[Int], value: Int, startIndex: Int, step: Int, continueCond: Int => Boolean, maxIncr: Int) {
var i = startIndex
var inc = 0
while (continueCond(i) && inc < maxIncr) {
if (arr(i) == value) {
arr(i) += 1
inc += 1
}
i += step
}
}
val arr1 = Array(1,4,1,5,1)
val arr2 = Array(1,4,1,5,1)
val arr3 = Array(1,4,1,5,1)
add1(arr1, 1, 0) // -> Array(2, 4, 2, 5, 2)
add1(arr2, 1, 2) // -> Array(2, 4, 2, 5, 1)
add1(arr3, 1, -2) // -> Array(1, 4, 2, 5, 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment