Search code examples
javaarraysmultidimensional-arraytic-tac-toe

Print 2d array as a literal "array of arrays" (read description)


This is a pretty niche problem, so please hear me out.

The Situation

I'm coding an Ultimate Tic Tac Toe game for the command line. I have a 2d char[9][9] array called currentState where each sub-array, which holds 'X', 'O', or ' ', represents a small 3x3 grid within the large 3x3 grid (index 0 is top left, 1 is top middle, 2 is top right, 3 is middle left, etc., for both the small grids and the large grid).

The Problem

If I were to try to print the array by iterating through it normally with two nested for loops, then the elements meant to display in each small grid would be displayed across a line. I want to print currentState so it will display in an "array of arrays" like the board is actually meant to look, as shown in the link above.

What I've Tried

I have created another int[9][9] called renderedState, with the idea being that it could be printed using nested for as described above; every element would correspond to the correct element in currentState (for example, currentState[3][7] == renderedState[5][1] -- the element in board 3 at position 7 should be printed on line 5, column 1 (both zero-based)).

The difficulty with this method is in finding a way to update this array given the indices of the square from currentState being updated (if currentState1[0] is being changed, renderedState[0][3] should also be changed). It took many failed attempts to come up with the following, which updates renderedState by looping through currentState:

for (int row = 0, board = 0; row < 9; row += 3)
    for (int col = 0; col < 9; col += 3, board++)
        for (int pos = 0; pos < 9; pos++)
            renderedState[row + (pos / 3)][col + (pos % 3)] = currentState[board][pos];

This works properly, but I plan to develop some sort of engine for the user to play against, so looping through all 81 elements to change a single value takes too much time for something that seems like it could be reduced to a single statement, like

renderedState[someRow][someColumn] = currentState[grid][pos];

...but how can I find the values for someRow and someColumn?

Sorry for the lengthy explanation. I've been trying to figure this out for so long that I'm getting confused myself. Please ask questions if something was unclear.


Solution

  • You can just calculate the values of someRow and someColumn out of the values grid and pos:

    someRow = Math.floor(grid / 3) * 3 + Math.floor(pos / 3); //each third grid-value the row increases by 3, each third pos-value it increases by 1
    someColumn = (grid % 3) * 3 + pos % 3; //The column is thrice the rest of grid divided by 3 plus the position divided by three
    

    This code works if, as you said, you are using a zero-based numbering system. Otherwise you need to use accordingly decremented values of grid and pos.