I am aware that there are solutions for shifting arrays out there. However no solution works for me. The code should achieve the following:
The method shift(int[] array, int places)
takes in an array
, shifts the elements places
- times to the right and replaces the "leftover" elements with "0".
So far I have:
public static int[] shiftWithDrop(int[] array, int places) {
if (places == 0 || array == null) {
return null;
}
for (int i = array.length-places-1; i >= 0; i-- ) {
array[i places] = array[i];
array[i] = 0;
}
return array;
}
This code does only somehow work, but it does not return the desired result. What am I missing?
CodePudding user response:
There are several issues in this code:
- It returns
null
whenplaces == 0
-- without shift, the original array needs to be returned - In the given loop implementation the major part of the array may be skipped and instead of replacing the first
places
elements with 0, actually a few elements in the beginning of the array are set to 0.
Also it is better to change the signature of the method to set places before the vararg array.
So to address these issues, the following solution is offered:
public static int[] shiftWithDrop(int places, int ... array) {
if(array == null || places <= 0) {
return array;
}
for (int i = array.length; i-- > 0;) {
array[i] = i < places ? 0 : array[i - places];
}
return array;
}
Tests:
System.out.println(Arrays.toString(shiftWithDrop(1, 1, 2, 3, 4, 5)));
System.out.println(Arrays.toString(shiftWithDrop(2, new int[]{1, 2, 3, 4, 5})));
System.out.println(Arrays.toString(shiftWithDrop(3, 1, 2, 3, 4, 5)));
System.out.println(Arrays.toString(shiftWithDrop(7, 1, 2, 3, 4, 5)));
Output:
[0, 1, 2, 3, 4]
[0, 0, 1, 2, 3]
[0, 0, 0, 1, 2]
[0, 0, 0, 0, 0]