javaarraysmultidimensional-arrayarray-indexing

Easier way to represent indicies in a 2D array


I'm new to programming and I've created a simple tic-tac-toe game. It took an input of the row and column of a 2d array. However, I want to make it simpler and use a value of 1-9 instead to represent each square on the board.

The way I've gone about this seems rather long and complex. Sorry about the bad formatting since I wanted to save space.

if (pos >= 0 && pos <= 9) { //checks if number is a valid position on the board
    if (pos == 1 && board[0][0] == ' ') { board[0][0] = xo; return true; }
    if (pos == 2 && board[0][1] == ' ') { board[0][1] = xo; return true; }
    if (pos == 3 && board[0][2] == ' ') { board[0][2] = xo; return true; }
    if (pos == 4 && board[1][0] == ' ') { board[1][0] = xo; return true; }
    if (pos == 5 && board[1][1] == ' ') { board[1][1] = xo; return true; }
    if (pos == 6 && board[1][2] == ' ') { board[1][2] = xo; return true; }
    if (pos == 7 && board[2][0] == ' ') { board[2][0] = xo; return true; }
    if (pos == 8 && board[2][1] == ' ') { board[2][1] = xo; return true; }
    if (pos == 9 && board[2][2] == ' ') { board[2][2] = xo; return true; }
}
return false;

The inner if statements check if the index is empty and then assigns the x or o depending on the number entered. If anyone knows any 'cleaner' and easier ways of doing this it would be much appreciated.


Solution

  • Assignment, Arithmetic, and Unary Operators

    You can get the coordinates of the cell [i][j] without loops at all, using only one variable pos in the range from 1 to 9:

    public static boolean isValid(int pos, char xo) {
        int i = (pos - 1) / 3; // row
        int j = (pos - 1) % 3; // column
        if (board[i][j] == ' ') {
            board[i][j] = xo;
            return true;
        }
        return false;
    }