Skip to content

Instantly share code, notes, and snippets.

@funyin
Last active October 16, 2022 23:51
Show Gist options
  • Save funyin/aaab51feaf6890e1ffa0a3cc26d4fa7c to your computer and use it in GitHub Desktop.
Save funyin/aaab51feaf6890e1ffa0a3cc26d4fa7c to your computer and use it in GitHub Desktop.
Rotate Array
/**
* 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