Created
July 7, 2017 18:07
-
-
Save blancosj/7478c27dabe08889fcfb29ada7649a3c to your computer and use it in GitHub Desktop.
This file contains 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
// ======================= | |
// Arrays: Left Rotation | |
// ======================= | |
def leftShift(input: Array[Int], rotations: Int): Unit = { | |
val tmpArray = new Array[Int](total) | |
val total = input.length | |
val pos = total - math.abs(rotations % total) | |
for (x <- 0 to total - pos - 1) { | |
tmpArray(pos + x) = input(x) | |
} | |
for (x <- 0 to pos - 1) { | |
tmpArray(x) = input(total - pos + x) | |
} | |
Array.copy(tmpArray, 0, input, 0, total) | |
} | |
var a = Array(1, 2, 3, 4) | |
leftShift(a, 2) | |
println(a.mkString(" ")) | |
// result: 3 4 1 2 | |
var a = Array(1, 2, 3, 4, 5, 6, 7) | |
leftShift(a, 15) | |
println(a.mkString(" ")) | |
// result: 2 3 4 5 6 7 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment