Paul D - 1 year ago 49
Java Question

# Moving array elements left and right

So as part of the

Vector
class I'm trying to create, I also want the ability for the user to be able to shift the elements in the array an
'n'
number of places depending on what is specified. If the user inputs a number that is larger than the array size, then the elements continue shifting back to the start and moving. An example would be:

 1 2 3 4 (shifted 1) => 4 1 2 3

1 2 3 4 (shifted 4) => 1 2 3 4

1 2 3 4 (shifted 5) => 4 1 2 3


I don't have much code so far except:

public Vector shifted(int amount) {
Vector vectorShifted = new Vector(length);

for (int i = 0; i < length; i++);
vectorShifted.elements[i] = this.elements[i + amount]
}
return vectorShifted;
}


However, when I run this program and a number greater than
length
is entered, an error is displayed. Is there a way of modifying this code in that any number, positive or negative can be inputted and shift the values across?

Change: vectorShifted.elements[i] = this.elements[i + amount]
to vectorShifted.elements[i] = this.elements[(i + amount) % length]
Integer[] array = {0,1,2,3,4}; Collections.rotate(Arrays.asList(array), 3); System.out.println(Arrays.toString(array)); //[2, 3, 4, 0, 1]