package username.graph; import java.util.Iterator; /** * An iterator for predecessors. * * @author Samuel A. Rebelsky * @version 1.0 of April 2006 */ public class MatrixPredecessors implements Iterator { // +------------------+-------------------------------------------------- // | Design Decisions | // +------------------+ /* (1) We keep a link to the the underlying adjacency matrix, rather than building a new array, vector, list, or whatever. (2) To iterate, we keep track of a position within that matrix. (3) We use nextPredecessor to keep track of the index of the next predecessor to be iterated. (4) If there are no predecessors, we set nextPredecessor to a value at least as large as this.size. */ // +--------+------------------------------------------------------------ // | Fields | // +--------+ /** The target. */ int target; /** The size of the underlying graph. */ int size; /** An adjaceny matrix to represent the edges. */ int[][] edges; /** The index of the next predecessor. */ int nextPredecessor; // +--------------+------------------------------------------------------ // | Constructors | // +--------------+ public MatrixPredecessors(int _target, int _size, int[][] _edges) { this.target = _target; this.size = _size; this.edges = _edges; this.nextPredecessor = 0; this.findPredecessor(); } // MatrixPredecessors(int, int[][]) // +------------------+-------------------------------------------------- // | Iterator Methods | // +------------------+ /** * Determine whether there are any more predecessors. */ public boolean hasNext() { return this.nextPredecessor >= this.size; } // hasNext() /** * Get the next predecessor. */ public Integer next() { // Grab the predecessor int succ = this.edges[this.target][this.nextPredecessor]; // Advance. ++nextPredecessor; // Find the next edge. findPredecessor(); // That's it. return succ; } // next() /** * Remove something. Not implements. */ public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } // remove() // +---------------+----------------------------------------------------- // | Local Helpers | // +---------------+ /** * Advance nextPredecessor to the first predecessor at or after its current * position. */ void findPredecessor() { while ( (this.nextPredecessor < this.size) && (this.edges[this.nextPredecessor][this.target] != MatrixWDG.NOEDGE) ) { ++this.nextPredecessor; } // while } // findPredecessor } // class MatrixPredecessors