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?

1
  • @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. Commented May 6, 2014 at 14:51

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

Comments

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;

4 Comments

Can you provide an example. This is not an answer, it's a comment.
@AnubianNoob: No, it was an answer. Just because it didn't have code to go with it, doesn't meant the question isn't answered.
Hmm, ok. It was really unclear without an example though.
On input {'n', 'i', 'c', 'k'} this returns 'ckcn'...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.