Last active
October 15, 2017 07:04
-
-
Save praveenKajla/5597227b433d0280e23fbb9975de2860 to your computer and use it in GitHub Desktop.
Write a function rotate(ar[], d, n) that rotates arr[] of size n by d element
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
//Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements | |
//https://www.youtube.com/watch?v=utE_1ppU5DY | |
//pass 1 | |
//1.copy first d elements in temp array | |
//2.move original array forward by d | |
//3.start updating vlues in originl array from n-d th position | |
// time complexity n space complexity d | |
function rotate1(arr=[],d){ | |
let n = arr.length | |
let temp = [] | |
//1 | |
arr.slice(0,d).map(a => temp.push(a)) | |
//2 | |
arr.slice(d,n).map((b,i) => arr[i] = b) | |
//3 | |
arr.slice(n-d,n).map((c,i) => arr[n-d+i] = temp[i]) | |
console.log(arr) | |
} | |
//pass 2 | |
//do d times | |
//move first element in array to temp(variable) | |
//shift every element to one left | |
//copy temp to last (empty) position of array | |
//time complexity O(n*d) space complexity O(1) | |
function rotate2(arr=[],d){ | |
let n = arr.length | |
let temp | |
[...Array(d).keys()].map(a => { | |
temp = arr[0] | |
arr.slice(1,n).map((b,i) => arr[i]=b) | |
arr[n-1] = temp | |
}) | |
console.log(arr) | |
} | |
//pass3 - juggling algorithm | |
//divide the arr in sets - gcd(n,d) sets | |
//outer loop from i = 0..gcd(n,d)-1 | |
//inner loop | |
//copy ith element to temp and i to j | |
//while(1) | |
//move (j+d)%n th element to jth positon | |
//updte j to (j+d)%n | |
// break while loop when (j+d)%n == i i.e. we reached end of loop | |
function rotate3(arr=[],d){ | |
let n = arr.length | |
let temp | |
let gcd = (a,b) => { | |
if(b==0)return a; | |
else return gcd(b,a%b) | |
} | |
[...Array(gcd(n,d)).keys()].map(i => { | |
temp = arr[i] | |
j = i | |
let k | |
while(1){ | |
k = (j+d)%n | |
if(k==i)break; | |
arr[j] = arr[k] | |
j=k | |
} | |
arr[j] = temp | |
}) | |
console.log(arr) | |
} | |
rotate3([1,2,3,4,5,6,7],2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment