Skip to content

Instantly share code, notes, and snippets.

@criskgl
Last active July 13, 2019 15:44
Show Gist options
  • Save criskgl/cfd027b9f8648de43aded9634902b559 to your computer and use it in GitHub Desktop.
Save criskgl/cfd027b9f8648de43aded9634902b559 to your computer and use it in GitHub Desktop.
/*
*In an array a
*figures out the element e
*in an index after performing r RIGHT rotations
*/
public class Tragaperras {
static int circularRightArrayRotation(int[] a, int r, int index) {
int l = a.length;
int R = r - (r/l*l);
//Get rid of over-rotations
//E.g
//length of array = 5
//rotations = 13
//we will only have to perform 2 rotations.
//13 - ((13/2)*5)
int e = 0;//element in index after rotations
int resultIndex = index - R;
if(resultIndex < 0){
resultIndex = a.length + resultIndex;
e = a[resultIndex];
}else{
e = a[resultIndex];
}
return e;
}
//PRO VERSION (same O(1) complexity, less code)
/*
static int circularArrayRotation(int[] a, int r, int index) {
int l = a.length;
int R = r - (r/l*l);
int result = 0;
int resultIndex = index - R;
return (resultIndex < 0) ? a[l+resultIndex] : a[resultIndex];
}
*/
public static void main(String[] args) {
int[] a = {1, 2, 3};
int r = 2;
int index = 0;
System.out.println(circularRightArrayRotation(a, r, index));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment