0

I need help rotating an array by a distance according to keyIndex.

Here is my code:

char[] arr = new char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
int keyIndex = 2;

char[] newArr = new char[26];

int last = arr[arr.length -1];
for (int i = 0; i < arr.length; i++) {
    arr[i] = arr[i + keyIndex];
}

but I get an error and the last two characters are not being saved in elements 0, 1.

My teacher said this can be solved somehow by using modulus division in one line.

7
  • What part of your code is even trying to handle this case? To even detect it? Commented Jan 27, 2022 at 0:27
  • 1
    What is last used for? (it's nothing at the moment, so you should delete it from your code) Commented Jan 27, 2022 at 0:34
  • okay. Do you have a solution for this? I am new to java and stack overflow and I don't know what I'm doing. Commented Jan 27, 2022 at 0:38
  • @Bohemian What is newArr used for? Commented Jan 27, 2022 at 0:41
  • @ScaryWombat I just removed it, I was trying to create a new array but decided to rotate the original one. Commented Jan 27, 2022 at 0:42

1 Answer 1

2

Replace your code's assignment line with this:

newArr[i] = arr[(i + keyIndex)%26];

The logic behind this is: % (i.e. modulus) gives us the remainder on the division by a given number.

let i = 25 and keyIndex=2, so arr[(25 + 2) % 26] => arr[27 % 26] => arr[1]

so we can say modulus26 bounds a number in the range of 0 to 26, which is the need for this rotation operation

Your Corrected Code:

char[] arr = new char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
int keyIndex = 2;
char[] newArr = new char[arr.length];
for (int i = 0; i < arr.length; i++) {
    newArr[i] = arr[(i + keyIndex )%arr.length];
} 
//Print Array
Sign up to request clarification or add additional context in comments.

15 Comments

or even % newArr.length for a more general solution. And how about some explanation?
So why should OP use modulus here? Please explain why this is necessary.
should not the assignment be to newArr ?
@passer-by if OP writes to newArr (which seems the original intention), instead of doing an in-place rotation, this problem is not an issue.
@Sharar294 this might be a good time to use a debugger. All Java IDEs support debugging. Halt execution and step through the code to see what happens.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.