0

For my second semester Java class we're currently working on a project that shifts an array of characters by a random generated number. So if the computer generated the number 2 and the characters were "nick" it would return it as "ckni." I can figure out shifting elements forward but I can't seem to get how to take the elements from the the end of the element and shift them to the front. Can anyone help me with this?

  • @dasblinkenlight I checked the question that was supposedly a duplicate. This question is about shifting all elements, the "duplicate" is about shifting a single element. The answer to these questions are different. – bcorso May 06 '14 at 14:51

2 Answers2

1

You shift everything forward as mentioned normally, but keep track on the index-counter. If suggested that you should shift to an index that is >= length, you substract the amount of length from the index

int shift = Random.nextInt(length);
char first = myarray[0];

int newindex = 0;
for(int i=0; i<myarray.length - 1; i++){
    int oldindex = newindex;
    newindex = newindex + shift;
    if(newindex >= myarray.length){
        newindex = newindex - myarray.length;
    }
    myarray[oldindex] = myarray[newindex];
}
myarray[newindex] = first;
Sara S
  • 679
  • 3
  • 6
1

Here are a couple of ways to shift depending on which data type you are starting with.

String

int shift = 2;
String str = "nick";
int pos = str.length() - shift;

// outputs 'ckni'
System.out.println(str.substring(pos, str.length()) + str.substring(0, pos));

List<Character>

List<Character> list = Arrays.asList('n', 'i', 'c', 'k');

Collections.rotate(list, shift);
// outputs [c, k, n, i]
System.out.println(list);

Character[]

Character[] array = {'n', 'i', 'c', 'k'};

Collections.rotate(Arrays.asList(array), shift);
// outputs 'ckni'
System.out.println(Arrays.asList(array));     

char[]

char[] carray = {'n', 'i', 'c', 'k'};
char[] rotated = new char[carray.length];
int pos = carray.length - shift;

System.arraycopy(carray, 0, rotated, shift, pos);
System.arraycopy(carray, pos, rotated, 0, shift);
// outputs 'ckni'
System.out.println(rotated);

Reversed Shifts

If you wrap shift in the modulo operator it will ensure the correct bounds and also let you reverse shift using negative values:

// shifts left by two
int shift = -2;
shift = (shift%str.length() + str.length())%str.length();
bcorso
  • 45,608
  • 10
  • 63
  • 75