Skip to content

Commit

Permalink
Create Rotate array
Browse files Browse the repository at this point in the history
  • Loading branch information
dishathakurata authored Nov 18, 2024
1 parent 1173186 commit 8ac451d
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions Rotate array
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
//Rotate array

import java.io.*;
import java.util.*;

class GFG {
public static void main(String args[]) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int t = Integer.parseInt(in.readLine().trim());

while(t-- > 0) {
String line = in.readLine();
String[] tokens = line.split(" ");
ArrayList<Integer> array = new ArrayList<>();

for(String token : tokens) {
array.add(Integer.parseInt(token));
}

int d = Integer.parseInt(in.readLine().trim());
int n = array.size();
int[] arr = new int[n];

for(int i = 0; i < n; i++) {
arr[i] = array.get(i);
}

new Solution().rotateArr(arr, d);
StringBuilder sb = new StringBuilder();

for(int value : arr) {
sb.append(value).append(" ");
}

out.println(sb.toString().trim());

out.println("~");
}
out.flush();
out.close();
}
}

class Solution {
static void rotateArr(int arr[], int d) {
int n = arr.length;
d = d % n;

reverse(d, n - 1, arr);
reverse(0, d - 1, arr);
reverse(0, n - 1, arr);
}

static void reverse(int start, int end, int[] arr) {
while(start <= end) {
int temp = arr[start];

arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
}

0 comments on commit 8ac451d

Please sign in to comment.