Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Iterator backed by an array of integers which it interprets as a set of pairs, where the first item of the pair indicates how many values should be returned, and the second item of the pair indicates the value to be returned.
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Iterator backed by an array of integers which it interprets as a set of pairs, where the
* first item of the pair indicates how many values should be returned, and the second
* item of the pair indicates the value to be returned. So, for example, when we iterate over the
* array <b>{3, 11, 0, 22, 2, 33}</b>, an ArrayIterator should return: <b><i>11, 11, 11, 33, 33</i></b>.
* <br>
* <br>
* We conceptualize the array as a linked list of nodes, each of which contains n integers of value x,
* where:
* <ul>
* <li>n = mArray[mIndex]</li>
* <li>x = mArray[mIndex + 1]</li>
* <li>mIndex = the ID of the node (where: ID % 2 == 0)</li>
* </ul>
*/
public class ArrayIterator implements Iterator<Integer> {
private int[] mArray;
private int mConsumed = 0;
private int mIndex = 0;
public ArrayIterator(int[] array) {
mArray = array;
}
@Override
public boolean hasNext() {
return hasNext(mIndex, mConsumed);
}
private boolean hasNext(int index, int consumed) {
if (!(index < mArray.length)) {
return false;
}
if (consumed < getNodeCapacity(index)) {
return true;
}
return hasNext(index + 2, 0);
}
@Override
public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
if (mConsumed < getNodeCapacity(mIndex)) {
mConsumed++;
return getNodeValue(mIndex);
} else {
mIndex += 2;
mConsumed = 0;
return next();
}
}
private int getNodeCapacity(int index) {
return mArray[index];
}
private int getNodeValue(int index) {
return mArray[index + 1];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.