Implement Circular Array
/*
* Career Cup 14.6
*
*/
package CareerCup;
import java.util.Iterator;
public class CircularArray<T> implements Iterable<T> {
private T items[];
private int head;
public CircularArray(int size) {
items = (T[]) new Object[size];
head = 0;
}
public int Size() {
return items.length;
}
public void rotate(int rightShift) {
if (rightShift < 0) {
rightShift += items.length;
}
head = (head + rightShift) % items.length;
}
public int convert(int index) {
int i = (index + head) % items.length;
return i;
}
public T get(int index) {
if (index < 0 || index >= items.length) {
throw new java.lang.IndexOutOfBoundsException();
}
int i = convert(index);
return items[i];
}
public void set(int index, T item) {
int i = convert(index);
items[i] = item;
}
@Override
public Iterator<T> iterator() {
return new CircularArrayIterator<T>(this);
}
private class CircularArrayIterator<TI> implements Iterator<TI> {
private int current = -1; //current reflects the offset from the rotated head
private TI[] refItems;
public CircularArrayIterator(CircularArray<TI> c) {
refItems = c.items;
}
@Override
public boolean hasNext() {
return current < refItems.length - 1;
}
@Override
public TI next() {
current++;
int i = convert(current);
return refItems[i];
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
/**
* @param args
*/
public static void main(String[] args) {
CircularArray<Integer> arr;
arr = new CircularArray<Integer>(5);
for(int i = 0; i < arr.Size(); i++) {
Integer in = new Integer(i + 10);
arr.set(i, in);
}
System.out.println("Before rotate...");
for(Integer i : arr) {
System.out.println(i);
}
System.out.println("After rotated...");
arr.rotate(2);
for(Integer i : arr) {
System.out.println(i);
}
}
}