简体   繁体   中英

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?

Just like lazary2 said, you can use the modulo operator %

Change: vectorShifted.elements[i] = this.elements[i + amount]

to vectorShifted.elements[i] = this.elements[(i + amount) % length]

If you want to use Array:

Integer[] array = {0,1,2,3,4}; Collections.rotate(Arrays.asList(array), 3); System.out.println(Arrays.toString(array)); //[2, 3, 4, 0, 1]

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