Skip to content

Instantly share code, notes, and snippets.

@keif
Created April 10, 2015 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keif/7af3fed695f2cb51be54 to your computer and use it in GitHub Desktop.
Save keif/7af3fed695f2cb51be54 to your computer and use it in GitHub Desktop.
Problem: Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
// Problem: Rotate an array of n elements to the right by k steps.
// For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
// How many different ways do you know to solve this problem?
var array = [1,2,3,4,5,6,7];
var result = [5,6,7,1,2,3,4];
// Solution 1 - Intermediate Array
function rotate(nums, k) {
var result = [],
i,
j = 0;
if (k > nums.length) {
k = k % nums.length;
}
for (i = 0; i < k; i++) {
result[i] = nums[nums.length - k + i];
}
for (i = k; i < nums.length; i++) {
result[i] = nums[j];
j++;
}
return result;
}
rotate(array, 3);
// Solution 2 - Bubble Rotate
function IllegalArgumentException(value) {
this.value = value;
this.message = "does not conform to the expected format for a zip code";
this.toString = function() {
return this.value + this.message;
};
}
function rotate(arr, order) {
if (arr == null || order < 0) {
throw new IllegalArgumentException("Illegal argument!");
}
var i,
j,
temp;
for (i = 0; i < order; i++) {
for (j = arr.length - 1; j > 0; j--) {
temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
}
}
return arr;
}
rotate(array, 3);
// Solution 3 - Reversal
function rotate(arr, order) {
order = order % arr.length;
if (arr == null || order < 0) {
throw new IllegalArgumentException("Illegal argument!");
}
// length of first part
var length = arr.length - order;
reverse(arr, 0, length - 1);
reverse(arr, length, arr.length - 1);
reverse(arr, 0, arr.length - 1);
return arr;
}
function reverse(arr, left, right) {
if (arr == null || arr.length == 1) {
return;
}
while(left < right) {
var temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
return arr;
}
rotate(array, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment