lightning345
lightning345

Reputation: 3

Java array rotation

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.

Upvotes: 0

Views: 114

Answers (1)

Anmol
Anmol

Reputation: 681

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

Upvotes: 2

Related Questions