Skip to content

Instantly share code, notes, and snippets.

@lucasrangit
Last active August 29, 2015 14:24
Show Gist options
  • Save lucasrangit/89a260c89cd3aed0444b to your computer and use it in GitHub Desktop.
Save lucasrangit/89a260c89cd3aed0444b to your computer and use it in GitHub Desktop.
A generic CircularArray class that can be efficiently rotated and is iterable.
/*
* A generic CircularArray class that can be efficiently rotated and is
* iterable.
*/
import java.util.Iterator;
public class CircularArray implements Iterable<Object> {
private Object[] a;
private int r;
public CircularArray(Object[] a) {
this.a = a;
this.r = 0;
}
public void rotate(int r) {
this.r = this.r + r % a.length;
}
/*
* How to implement a Java Iterable class: https://stackoverflow.com/questions/5849154/can-we-write-our-own-iterator-in-java
*/
@Override
public Iterator<Object> iterator() {
Iterator<Object> it = new Iterator<Object>() {
private int index = r > 0 ? a.length - r : Math.abs(r);
@Override
public boolean hasNext() {
return index < (r > 0 ? a.length - r + a.length : Math.abs(r) + a.length );
}
@Override
public Object next() {
return a[index++ % a.length];
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
return it;
}
public static void main(String[] args) {
Integer[] a = new Integer[]{0, 1, 2, 3, 4};
CircularArray ca = new CircularArray(a);
int r = Integer.parseInt(args[0]);
// before
for (Integer i : a) {
System.out.print(i + " ");
}
System.out.println();
// rotate
ca.rotate(r);
System.out.println(r);
// after
for (Object o : ca) {
System.out.print(o + " ");
}
System.out.println();
}
}
@lucasrangit
Copy link
Author

Works with both positive and negative rotation values.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment