We have a method in which an array and number of rotations are passed as input and we have to return the array after left rotations. Here is my solution.
static int[] rotLeft(int[] a, int d) {
int i = 0;
int logicBreak = d;
int[] copy = new int[a.length]; // SEE HERE GUYS, WHY THIS WORKS
int[] copy = a; // AND WHY NOT THIS,
while(logicBreak < a.length){
copy[i] = a[logicBreak];
i++;
logicBreak++;
}
logicBreak = 0;
while(logicBreak < d){
copy[i] = a[logicBreak];
i++;
logicBreak++;
}
return copy;
}
I hope that there is no confusion until now and if you have then, open this page. So my problem is really basic. Why the answer works when I do this int[] copy = new int[a.length]; but does not work when I do this int[] copy = a;. Can you tell me the difference, because we are changing all the values of copy array, so what is the matter we make it new int[] or same as the array a. I have created an android app but I am still not getting this array concept, if there is a difference then please tell me.
For your ease here is the full code.
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the rotLeft function below.
static int[] rotLeft(int[] a, int d) {
int i = 0;
int logicBreak = d;
int[] copy = new int[a.length];
while(logicBreak < a.length){
copy[i] = a[logicBreak];
i++;
logicBreak++;
}
logicBreak = 0;
while(logicBreak < d){
copy[i] = a[logicBreak];
i++;
logicBreak++;
}
return copy;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String[] nd = scanner.nextLine().split(" ");
int n = Integer.parseInt(nd[0]);
int d = Integer.parseInt(nd[1]);
int[] a = new int[n];
String[] aItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < n; i++) {
int aItem = Integer.parseInt(aItems[i]);
a[i] = aItem;
}
int[] result = rotLeft(a, d);
for (int i = 0; i < result.length; i++) {
bufferedWriter.write(String.valueOf(result[i]));
if (i != result.length - 1) {
bufferedWriter.write(" ");
}
}
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}