Reputation: 11
I want to shift my elements in the array multiple times:
for example: Old array: (1,2,3 ,4 5) shift 3 steps New array: (3, 4, 5, 1, 2)
I created this function but it only shifts 1 step:
public static int[] shiftmultiple(int[] array1, int shiftCount) {
int[] array2 = new int[array1.length];
for(int i = 0; i < shiftCount; i++){
for(int j = 0; j < array1.length-1; j++){
array2[j+1] = array1[j];
}
array2[0] = array1[array1.length-1];
}
return array2;
}
P.S. I need to make new array since that is the required instruction.
Upvotes: 0
Views: 322
Reputation: 2202
Use only one cycle. New element index is greater than old on shiftCount value, but if it is greater than array1.length-1 then in order to make cyclic shift, take new position as substraction of new index and array1.length. This can be interpreted by calculation of reminder of devision new index by array1.length.
public static int[] shiftmultiple(int[] array1, int shiftCount) {
int[] array2 = new int[array1.length];
for(int i = 0; i < array1.length; i++)
array2[(i+shiftCount)%array1.length] = array1[i];
return array2;
}
Upvotes: 0
Reputation: 109547
Ask yourself what array2
is filled at i
with at what index in array
.
for (int i = 0; i < array.length; i++) {
int j = ... i ... shiftCount ...;
array2[i] = array[j];
}
For shiftCount 0, j = i;
. What for 1, 2, 3?
Useful is the modulo operator %
or an if
statement for starting at 0 again.
shiftCount | i | 0 | 1 | 2 | 3 | 4 |
---|---|---|---|---|---|---|
0 | j | 0 | 1 | 2 | 3 | 4 |
1 | j | 1 | 2 | 3 | 4 | 0 |
2 | j | 2 | 3 | 4 | 0 | 1 |
3 | j | 3 | 4 | 0 | 1 | 2 |
Upvotes: 1
Reputation: 23
Your approach might work, except that you create array2 from the contents of array1, then repeat the process (creating array2 from array1). Overwriting the same information instead of taking the previous answer and working from there.
However your solution is quite inefficient (even once fixed) requiring scanning through the entire array each time you shift. Can I recommend you look at the modulus (%) operator instead? Using this you can assign everything with a single pass.
Upvotes: 0