• Some users have recently had their accounts hijacked. It seems that the now defunct EVGA forums might have compromised your password there and seems many are using the same PW here. We would suggest you UPDATE YOUR PASSWORD and TURN ON 2FA for your account here to further secure it. None of the compromised accounts had 2FA turned on.
    Once you have enabled 2FA, your account will be updated soon to show a badge, letting other members know that you use 2FA to protect your account. This should be beneficial for everyone that uses FSFT.

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