Can someone tell how to fix this code so instead of moving the arrays to the right how do i make it move to the left? Can someone please explain it to me too
public class Test {
public static void main(String[] args) {
int[] b = {10, 20, 30, 40, 50, 60};
System.out.println("\n///// Rotate Left k cell example \n////");
b = copyArray(a, a.length);
b = rotateLeft(b,4); //assuming k = 4
printArray(b); // This Should Print: { 50, 60, 10, 20, 30, 40 };
}
// Rotates all the elements of the source array to the right by 'k' positions
// Returns the updated array
public static int[] rotateLeft(int[] source, int k) {
int[] arr = copyArray(source,source.length); //copies all source to a new array
int[] temp = new int[arr.length];
for (int i = 0; i < arr.length; i++){
temp[(i + k) % arr.length] = arr[i];
}
for (int i = 0; i < arr.length; i++){
arr[i] = temp[i];
}
return arr;
}
}
So this code rotates the elements to the right side. How should i modify it so that it rotates it to the left side?
Output i am getting:
{ 30, 40, 50, 60, 10, 20 }
but my desired output is:
{ 50, 60, 10, 20, 30, 40 }
I think you can just change your assignment logic for populating the temp
array. Change this line:
temp[(i + k) % arr.length] = arr[i];
to this:
temp[i] = arr[(i + k) % arr.length];
The logic here is that the ith
entry in temp[]
will equal the entry k
steps ahead of it in arr[]
. In other words, temp[]
will contain the original elements shifted to the left by k
. Note that you still need the mod operation to make sure that indexing wraps around the size of the array.
Full code:
public static int [] rotateLeft(int [] source, int k){
int arr[] = copyArray(source, source.length);
int[] temp = new int[arr.length];
for (int i=0; i<arr.length; i++) {
temp[i] = arr[(i + k) % arr.length];
}
for (int i=0; i<arr.length; i++) {
arr[i] = temp[i];
}
return arr;
}
Basically do (i - k)
instead of (i + k)
. On top of that, remove the copyArray
call and the second loop. And because the %
operator in java behaves the it does, you have to add source.length
to (i - k)
before actually %
ing it:
public static int [] rotateLeft(int [] source, int k) {
int arr[] = new int[source.length];
for (int i = 0; i < arr.length; i++){
arr[(i - k + source.length) % source.length] = source[i];
}
return arr;
}
Outputting
50
60
10
20
30
40
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.