dante dante - 7 months ago 17
Java Question

How to shift N times last element of the list on top

I got array of ints, and I want in order to last element of this array will be shift on top N times, something like this:

int[] array = {1, 2, 3, 4, 5};


And now, last element will be shifted for examaple 3 times, and it should be expected result:

3, 4, 5, 1, 2


I tried like this:

int[] tab = new int[5];
tab[0] = 1;
tab[1] = 2;
tab[2] = 4;
tab[3] = 5;
tab[4] = 6;

int[] secondTab = new int[5];
int N = 3;
int j = 0;

for (int i=0; i<tab.length-1; i++){
secondTab[i] = tab[(tab.length-1)-N];
N--;
if (secondTab[i+1]==0){
secondTab[i+1] = tab[j];
}
}


It's obviously bad code, j is not getting increment at all so it works only for this example, but I'm wondering what is the best way to do it?

Answer

If you want to shift right N times, it means the element at the i-th position will be at the (i+N)%tab.lenth-th position:

for (int i = 0; i < tab.length; i++) {
    secondTab[(i+N)%tab.length] = tab[i];
}