Skip to content

Instantly share code, notes, and snippets.

@lelandjansen
Created January 20, 2016 01:39
Show Gist options
  • Select an option

  • Save lelandjansen/51dee9e76a6955131c59 to your computer and use it in GitHub Desktop.

Select an option

Save lelandjansen/51dee9e76a6955131c59 to your computer and use it in GitHub Desktop.
Rotates an array K times to the right
/*
Task description
A zero-indexed array A consisting of N integers is given. Rotation of the array
means that each element is shifted right by one index, and the last element of
the array is also moved to the first place.
For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7]. The
goal is to rotate array A K times; that is, each element of A will be shifted to
the right by K indexes.
Write a function that, given a zero-indexed array A consisting of N integers and
an integer K, returns the array A rotated K times.
For example, given array A = [3, 8, 9, 7, 6] and K = 3, the function should
return [9, 7, 6, 3, 8].
Assume that:
N and K are integers within the range [0..100];
each element of array A is an integer within the range [−1,000..1,000].
*/
function computeGcd(a, b) {
return b?computeGcd(b, a%b):a;
}
function rotateArray(A, K) {
N = A.length;
if (!N) return [];
var gcd = computeGcd(N, K);
for (var i = 0; i < gcd; i++) {
var x = i, t1, t2 = A[x];
for (var j = 0; j < N/gcd; j++) {
t1 = t2;
t2 = A[(x+K)%N];
A[(x+K)%N] = t1;
x = (x+K)%N;
}
}
return A;
} // End of rotateArray
// That's all folks!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment