Given an array of integers.
Inside the for loop, firstly, I'm making a copy of the initial array to a new array. Then the last element is being removed and the rest elements are being rotated by one to the right.
That means the element at index 0 will go to index 1, and so on, and the element will go to index 0.
At this point, I am facing the issue. The previous result has to be a source for the subsequent iteration.
The process continues until there's only one element left in the array.
Here is the code I have:
int[] arr= {1,2,3,4,5}; // orignal array
int[] newArr = new int[arr.length];
int[] result = new int[newArr.length];
for(int i = 1;i<n;i++)
{
newArr = Arrays.copyOf(arr, arr.length - i);
System.out.println(Arrays.toString(newArr));// here i am deleting one array at last,
// code works fine upto here. but i want the next step as below commented code to perform in loop. which i am really unable to do.
//System.arraycopy(newArr, 0, result, 1, newArr.length - 1);
//result[0] = newArr[newArr.length - 1];
//result = Arrays.copyOf(result,result.length-1);
//System.out.println(Arrays.toString(result));
}
output should come like this
[1, 2, 3, 4, 5] // original array
[1, 2, 3, 4] // array after deletion
[4, 1, 2, 3] // array after rotaion
[4, 1, 2]// again after deletion from previous array
[2, 4, 1]// array after rotaion
[2, 4]// again after deletion from previous array
[4, 2]// array after rotation
[4]
final answer is 4