Skip to content

Instantly share code, notes, and snippets.

@daanta-real
Created August 25, 2021 00:47
Show Gist options
  • Save daanta-real/85d267cd0345177a9df5e40ed42fe6dd to your computer and use it in GitHub Desktop.
Save daanta-real/85d267cd0345177a9df5e40ed42fe6dd to your computer and use it in GitHub Desktop.
Array Circulator : circulate an single dimension array with the times and the direction what you want
public class c01_ArrayShifter {
// Circulate the number in case of overflow
private static int chk_overflow(int num, int len) {
return num >= len ? (num - len)
: num < 0 ? (num + len)
: num;
}
// Circulate an array with the times and the direction what you want
// - Object[] arr: Target Array which has a Single dimension
// - int directionAmount: 1 = Forward, -1 = Backward
// - int times: How many times do you want to push (Forward/Backward)
public static Object array_shift(Object[] arr, int directionAmount, int times) {
int currPos, nextPos;
Object temp;
for(int i = 0; i < times; i++) {
for(int j = 0; j < arr.length - 1; j++) {
// Calculate the current and next positions
currPos = chk_overflow( j * directionAmount, arr.length);
nextPos = chk_overflow((j + 1) * directionAmount, arr.length);
// Swap the elements of the current and next positions
temp = arr[nextPos];
arr[nextPos] = arr[currPos];
arr[currPos] = temp;
}
}
return arr;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment