Ani D. Ani D. - 10 days ago 5
Java Question

Update array with resulting array from calling a function

I am trying to update an array with the resulting array after providing the original one as a parameter to a function. I am not sure how to achieve this. I haven't covered all the material yet and I need your help. So what I am trying to achieve:

Original array: [1, 2, 3, 4, 5, 6]

n = 3 where n is the number of times the elements of the array will be shifted to the right

Shifted array: [4, 5, 6, 1, 2, 3]

I've created a method that shifts by 1 position. I have another method to switch by N positions where I call the method switching by 1 position. It switches the array once, but then I cannot update my original array with the result from the shifting. So instead of getting:

Original array: [1, 2, 3, 4, 5, 6]
RIGHT SHIFT: [6, 1, 2, 3, 4, 5]
RIGHT SHIFT: [5, 6, 1, 2, 3, 4]
RIGHT SHIFT: [4, 5, 6, 1, 2, 3] --> **final result** <br>


I get:

Original array: [1, 2, 3, 4, 5, 6]
RIGHT SHIFT: [6, 1, 2, 3, 4, 5]
RIGHT SHIFT: [6, 1, 2, 3, 4, 5]
RIGHT SHIFT: [6, 1, 2, 3, 4, 5]


My code:

public class Shift {

public static int[] rotate(int[] seq){
int[] origArr = seq;
int[] shiftedArrR = new int[seq.length];

for (int i = 0, j = i+1; j < origArr.length; i++, j++) {
shiftedArrR[j] = origArr[i];
}
shiftedArrR[0] = origArr[origArr.length-1];

System.out.print("RIGHT SHIFT: ");
System.out.println(java.util.Arrays.toString(shiftedArrR));
return shiftedArrR;
}

public static void rotate(int[] seq, int times){

System.out.println(java.util.Arrays.toString(seq));
int[] temp = new int[seq.length];

for (int i = 1; i <= times; i++) {
temp = rotate(seq);
}
}


// ------------ MAIN METHOD ----------------
public static void main(String[] args) {

System.out.print("Original array: ");
rotate(new int[]{1,2,3,4,5,6}, 3);
}

}


Apparently the result of rotate(seq) is not assigned to the seq which is provided to the rotate() method which is supposed to shift it more times.
I know it is something very simple and I tried different ways to fix this, but with no luck.

Answer
public static void rotate(int[] seq, int times){

    System.out.println(java.util.Arrays.toString(seq));
    for (int i = 1; i <= times; i++) {
        seq = rotate(seq);
    }
}

replace your rotate method with this code. you always rotate the same array with rotate(seq). since you save it in temp you have the problem of calling the method with seq instead of temp. therefore change content of for loop to seq = rotate(seq);. this saves the output from your second rotate method in the array which you the pass again into the method

Comments