Created
August 2, 2012 01:04
-
-
Save cb372/3232116 to your computer and use it in GitHub Desktop.
Scala solution to http://blog.jazzychad.net/2012/08/01/array-iteration-problem.html (while loop, in-place)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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