212k views
0 votes
Write another version of the shift method that modifies the parameter instead of returning a new 2D array. For example, if arr contains {{1,2,3},{4,5,6}}, then after executing shift(arr),arr should contain {{2,3,1},{5,6,4}}.

public static void shift(int[][] arr) {

1 Answer

3 votes

Final answer:

The shift method in question is for cyclically shifting the elements of each row in a 2D array to the right. By storing the last element, shifting right, and placing the stored value at the start, the original array is modified directly.

Step-by-step explanation:

To modify the parameter arr such that the shift method rearranges the elements within each row of a 2D array, one can loop through each row and perform a right shift operation. This can be done by temporarily storing the last element of each row, shifting all elements to the right by one position, and then placing the stored last element at the beginning of the row.

public static void shift(int[][] arr) {
for (int row = 0; row < arr.length; row++) {
int lastElement = arr[row][arr[row].length - 1];
for (int col = arr[row].length - 1; col > 0; col--) {
arr[row][col] = arr[row][col - 1];
}
arr[row][0] = lastElement;
}
}

This code modifies arr directly, and after calling shift(arr), the original 2D array will have its rows cyclically shifted to the right.

User Kaboomfox
by
7.6k points