Wednesday, June 15, 2011

Loop around an array in said direction

/*
 * Class to loop an array of elements in said direction.
 */

package logic;

/**
 *
 * @author Nageswara Rao. V
 */
public class LoopArray {

    int dir = 1; // direction +1 -> forward, -1 -> reverse
    int startPos = 0; // init at zero position
    int[] source = new int[0]; // source array
    int curPos = 0; // current position in iterator
    boolean hasNext = false; // next available?

    /**
     * setter for loop direction
     *
     * @param inDir - direction of loop
     */
    public void setDirection(int inDir) {
        if(inDir > 0) {
            dir = 1;
        } else if (inDir < 0) {
            dir = -1;
        }
    }

    /**
     * setter for source array
     *
     * @param src - source array
     */
    public boolean setSource(int[] src) {
        if(src.length > 0) {
            source = src;
            hasNext = true;
            return true;
        }
        return false;
    }

    /**
     * setter for position to start looping
     *
     * @param src - source array
     */
    public boolean setStartPos(int pos) {
        if(pos > 0 && pos < source.length) {
            startPos = pos;
            curPos = pos;
            return true;
        }
        return false;
    }

    /**
     * acessor of next status
     *
     */
    public boolean hasNext() {
        return hasNext;
    }

    /**
     * calculates next position
     *
     * @param src - source array
     */
    private int getNextPos() {
        int lcurrent = (curPos+dir+source.length) % source.length;;
        return lcurrent;
    }

    /**
     * returns next value and resets current pointer
     *
     * @param src - source array
     */
    public int next() {
        int value = source[curPos];
        int nxtPos = getNextPos();
        if((hasNext = (startPos != nxtPos))) {
            curPos = nxtPos;
        }
        return value;
    }

    /**
     * reset current position and hasNext status
     *
     * @param src - source array
     */
    public void reset() {
        curPos = startPos;
        hasNext = true;
    }

    public static void main(String args[]) {
        int[] src = {90, 80, 70, 60, 50, 40, 30, 20, 10, 00};
        LoopArray bdt = new LoopArray();
        bdt.setSource(src);
        bdt.setDirection(-1);
        bdt.setStartPos(src.length-1);
        while(bdt.hasNext()) {
            System.out.println(bdt.next());
        }
    }
}

No comments:

Post a Comment