user3529573
user3529573

Reputation: 19

Java- Iterating backwards through Array under a condition

So for one of my game models, there is an array of elements represented as a string "--X-X" so that this board has 5 boxes, and positions are 0-4. Each 'X' can only move left. There is an "X-Index" so that if I run getIXPosition(1) it will return the position of the first X which is 2. And getXPosition(2) will return second X's position which is 4. So the string board is "--X-X" but in my code it's represented as an array as "00102" so that I can keep track of xIndex.

Now my issue is that I need to make a move method that prevents the second x from skipping over the first X into position 1 or 0. That is not allowed in this game. I thought I wrote the method correctly but my tests aren't passing when I test to make sure second X can not hop over any X's before it.

public void move(int xIndex, int newPosition) 
{
    int oldPosition = getXPosition(xIndex);

    for(int i= oldPosition - 1; i >= 0;i--) 
    {
        while (board[i] == 0 ) 
        {
            board[oldPosition] = '0'; // so this spot is open '-'
            board[newPosition] = xIndex;
        }
        throw new IllegalArgumentException("Error cannot move X to new position");  
    }
}

What am I doing wrong?

Upvotes: 0

Views: 75

Answers (2)

async
async

Reputation: 1537

I think the code is a bit flawed. First, I don't think you need to iterate all the way to 0. You should only iterate until you hit newPosition.

Then the while loop doesn't make much sense. I think you were after an if.

Lastly, personally I wouldn't throw an IllegalArgumentException in this case (actually, you're throwing after the first iteration regardless, so that's another flaw). It's the state of the board that's problematic, not the arguments. I would maybe throw IllegalArgumentException if one of the arguments was negative etc.

public void move(int xIndex, int newPosition) {
    int oldPosition = getXPosition(xIndex);

    for(int i= oldPosition - 1; i >= newPosition; i--) {
        if(board[i] == '0') {
            board[oldPosition] = '0';
            board[i] = xIndex;
            oldPosition = i;
        } else {
            //throw some custom exception; we found the other X here.
        }
    }
}

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533620

If you know the position you want to move to, you don't have to search for it, just move there.

if (board[newPosition] == '0') {
   board[newPosition[ = xIndex;
   board[oldPosition] = '0';
} else {
   throw new IllegalArgumentException("Error cannot move X to new position"); 
}

Note: The character '0' is not the value 0 (Actually it is 48 in ASCII)

Upvotes: 1

Related Questions