Skip to content

Instantly share code, notes, and snippets.

@mayonesa
Created February 6, 2022 22:26
Show Gist options
  • Save mayonesa/e92774f05833e6895fa173b9192e1257 to your computer and use it in GitHub Desktop.
Save mayonesa/e92774f05833e6895fa173b9192e1257 to your computer and use it in GitHub Desktop.
object ArrayRotation {
def rotate(a: Array[Int], k: Int): Array[Int] = {
val n = a.length
lazy val kRn = k % n
if (n == 0 || kRn == 0)
a
else
Array.tabulate(n) { i =>
val j = i - kRn
if (j < 0) a(j + n)
else a(j)
}
}
}
import org.scalatest.flatspec.AnyFlatSpec
class ArrayRotationSpec extends AnyFlatSpec {
private val a = Array(1, 2, 3, 4)
"shifting by length" should "no-effect" in {
assert(ArrayRotation.rotate(a, 4) === a)
}
"n = 0" should "no-effect" in {
assert(ArrayRotation.rotate(Array(), 5).isEmpty)
}
"k = 0" should "no-effect" in {
assert(ArrayRotation.rotate(a, 0) === a)
}
"shifting once" should "work" in {
assert(ArrayRotation.rotate(a, 1) === Array(4, 1, 2, 3))
}
"shifting twice" should "work" in {
assert(ArrayRotation.rotate(a, 2) === Array(3, 4, 1, 2))
}
"fully rotating more than once" should "work" in {
assert(ArrayRotation.rotate(a, 10) === Array(3, 4, 1, 2))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment