Last active
October 16, 2022 23:51
-
-
Save funyin/aaab51feaf6890e1ffa0a3cc26d4fa7c to your computer and use it in GitHub Desktop.
Rotate Array
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
/** | |
* Given an array, rotate the array to the left by k steps where k is non-negative | |
* | |
* Input: [1,2,3,4,5,6,7] ans k = 2 | |
* Output: [3,4,5,6,7,1,2] | |
*/ | |
fun main(){ | |
val array = intArrayOf(1,2,3,4,5,6,7) | |
val k = 3 | |
print(array.leftShit(k).asList()) | |
} | |
fun IntArray.leftShit(k:Int):IntArray{ | |
var rotateBy = k | |
if(k>size) | |
rotateBy %=size | |
var shiftedArray = this.copyOf() | |
repeat(rotateBy){ | |
shiftedArray = intArrayOf(*shiftedArray.copyOfRange(1, size),shiftedArray.first()) | |
} | |
return shiftedArray | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment