Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Tic Tac Toe

Name: Anonymous 2010-02-21 14:53

Does /prog/ know an efficient algorithm to check for a win/loss/draw in the game of Tic Tac Toe?

Let board be an array of integers where same numbers represent same players or blank, e.g. -1 and 1 for the players and 0 for blank.

Is there a more efficient alternative than checking it like this:
// check if player "1" won:
if ((board[0] == 1 && board[1] == 1 && board[2] == 1)
 || (board[3] == 1 && board[4] == 1 && board[5] == 1)
 || (board[6] == 1 && board[7] == 1 && board[8] == 1)
 || (board[0] == 1 && board[3] == 1 && board[6] == 1)
 || (board[1] == 1 && board[4] == 1 && board[7] == 1)
 || (board[2] == 1 && board[5] == 1 && board[8] == 1)
 || (board[0] == 1 && board[4] == 1 && board[8] == 1)
 || (board[2] == 1 && board[4] == 1 && board[6] == 1)) {
    // player "1" won
}


This is ucking fugly.

Name: Anonymous 2010-02-21 15:44

0 1 2
3 4 5
6 7 8

if ((board[4] == 1 && ((board[0] == 1 && board[8] == 1)
                    || (board[2] == 1 && board[6] == 1)
                    || (board[1] == 1 && board[7] == 1)
                    || (board[3] == 1 && board[5] == 1))
 || (board[0] == 1 && ((board[1] == 1 && board[2] == 1)
                    || (board[3] == 1 && board[6] == 1))
 || (board[8] == 1 && ((board[2] == 1 && board[5] == 1)
                    || (board[6] == 1 && board[7] == 1)))

my worst case: 6 comparisons
your worst case: 10 comparisons

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List