简体   繁体   中英

Move array to left and right

I am using java in eclipse. I am trying to solve two problems. I know how to move an array to the right or left by one and fill in the last element with the first or the first with the last. I am now trying to move an array, say, three indices to the right OR three indices to the left. Is someone able to assist? I do not want to use modulus.

exmample, my array is {1,2,3,4,5} : and im rotating this to the left by three indexes if x is negative, so in this case: x = -3

if (x < 0) {
  for (i = length1 - 2, j = 0; j < (length1 - Math.abs(x)); i++, j++) {
        temp[i] = myArray[j];
  }
  for (i = 0, j = (length1 - Math.abs(x)); j < length1; i++, j++) {
        temp[i] = myArray[j];
  }
}

This will not run unless in my first for loop, I have: i = length1 - 2 .

Is there a more universal way to do this? What if I'm trying to rotate the number by 23 indexes, how would I go about doing that?

input 1,2,3,4,5 output 4,5,1,2,3

you can use a very simple algorithm to shift the positions of your array to the right or to the left:

You start with an empty array and iterate over your initial array, you skip N positions and then fill in order, adding what you skipped to the index and using % modulus to ensure that you get back to the begining once you reach the end

If you want to allow negative numbers, you can also add the original array to ensure always positive numbers and bound the shift using modulus again, so the shift never gets too large, because shifting an array of three elements, three times is like not doing anything

Here is some code example: (its actually javascript, to make it so you can run it here, but you get the idea and syntaxis is very similar

 function moveBy(array, num){ num = num % array.length; // bounds the shift let result = new Array(array.length); // inits empty array for (let i = 0; i < array.length; i++) { let mappedIndex = (i + num + array.length) % array.length; result[i] = array[mappedIndex]; // skips num elements and fills everything using % to get back to the begining once reached the end } return result; } let example = [1,2,3,4,5]; console.log(moveBy(example, 1)); console.log(moveBy(example, 3)); console.log(moveBy(example, -2));

public void move(int[] nums, int k) {
    
    k = k % nums.length;
    
    // Reverse the orginal array.
    swap(nums, 0, nums.length - 1);
    
    // Reverse the left portion.
    swap(nums, 0, k - 1);
    
    // Reverse the right portion.
    swap(nums, k, nums.length - 1);
}    

private void swap(int[] nums, int l, int r) {
    while (l <= r) {
        
        int temp = nums[l];
        nums[l] = nums[r];
        nums[r] = temp;
        
        l++;
        r--;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM