Take Your Turn – Solution

This month’s Exercise is to simulate turns in a game of tic-tac-toe (naughts and crosses). So the solution requires that you randomly work through available squares in the game matrix, alternating placement of an 'x' or 'o' token.

In the sample code, a for loop places random 'x' or 'o' characters in the grid[] array. For my solution, however, I chose to use a while countdown loop instead.

Within the countdown loop, a randomizer attempts to place a token for 'x' or 'o', depending on the value of the countdown variable (odd or even). When a token is placed, the countdown variable is incremented, otherwise the loop keeps spinning until an empty grid space is found.

Here is the countdown loop portion of my solution that places tokens in the game matrix:

    /* fill the grid */
    x = 0;
    while(x<9)
    {
        if(x%2) /* set 'x' token */
        {
            r = rand() % 9;
            if(grid[r] == ' ')
            {
                grid[r] = 'x';
                x++;
            }
        }
        else    /* set 'o' token */
        {
            r = rand() % 9;
            if(grid[r] == ' ')
            {
                grid[r] = 'o';
                x++;
            }
        }
    }

Variable x is a counting variable. It references all 9 squares in the matrix, but not a specific array element. It just ensures that the while loop spins 9 times. (And it counts up, not down, but I still refer to the structure as a countdown loop.)

The if statement at Line 17 (in the final code) is triggered for even counts of variable x. That’s when the 'x' token is placed. When x is odd, the else statement at Line 26 runs and the code attempts to place an 'o' token. In the big picture, this process is how the simulation takes turns placing each token.

Just because the if or else statements are run, however, doesn’t guarantee that a token is placed.

Within each set of statements (if at Line 17 or else at Line 26), variable r contains a random value, 0 through 8, representing an element in array grid[] — a location in the game matrix. An if statement checks to see whether that element is available. If so, the token is placed (Lines 22 and 31) and variable x is incremented. If not, the while loop continues to spin; variable x isn’t incremented.

The while loop may repeat several dozen times, especially as the value of variable x increases. It take longer to locate available elements as the grid[] array fills. Granted, this technique may not be very efficient, but it works to evenly-distribute the tokens.

Click here to view my full solution.

Here are a few sample runs:

 x  o  x
 o  o  o
 x  x  o

 o  o  x
 o  x  x
 x  o  o

 x  o  o
 x  x  o
 x  o  o

As you can see, the tokens are distributed evenly in each simulation.

My solution is only one approach to solving the problem. If your solution generates output that shows tokens distributed in a proper manner, then great!

Leave a Reply