Java Array Rotation

AMD_RULES

2[H]4U
Joined
Mar 26, 2007
Messages
3,010
I'm trying to write a method that will rotate a set of values in an array. For example, say I have {1, 2, 3, 4, 5, 6}... it should print {5, 6, 1, 2, 3, 4}

Here's what I have so far and it prints weird characters:

Code:
public static void rotate(int[] values, int distance)
    {
        for (int i = 0; i < distance; i++){
            int temp = values[0];
            int j = 0;
            for(j = i; j < distance - 1; j++){
                values[j] = values[j + 1];
            }
        }
        System.out.println(values);
    }
 
either use
System.out.println(java.util.Arrays.toString(values));
or if that's not suitable you'll have to write code to loop through the array and convert each int to its String representation.
 
you would use 1 loop only. it start at the beginning through the middle of the array.
it swaps the values at the loop counter with the value at the end minus the loop counter
a swap is something like t = x; x = y; y = t. what you have above is destroying data.

oops: gave another look, I thought you were reversing. a rotation will be somewhat different.

ok, the easy way is just to make a second array the same size as the first.
You need to iterate through all the elements.
the element in the new array gets the same as the element in the previous
array + distance. You need to check for out of bound conditions. if less than 0
you need to pull from the end. if >= than sizeof, then pull from the beginning.


you can do it with a single array, assuming you xor all the elements, but
most likely that will just cause problems and confuse people.
 
Last edited:
The mod function (%) is your friend. If you know how to use it, the problem becomes trivial.
 
Back
Top