• Create Account

## Best way to traverse a 2d array to dertermine the winner in Tic-Tac-Toe

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

18 replies to this topic

### #1Random2323  Members

230
Like
0Likes
Like

Posted 14 August 2014 - 04:15 AM

I have created a 3x3 matrix for a tic tac toe game that stores the condition of the gameboard . Each cell  stores the value 1 if the particular place of the board is occupied with a circle or 2 if it's occupied with an X. What's the best way to determine the winner as in best way to traverse the matrix and find where there are 3 consecutive symbols of a kind ?

5832
Like
5Likes
Like

Posted 14 August 2014 - 05:25 AM

POPULAR

Do it in the way that is easiest for you, the reader of the code, to understand.

Although a good idea would be to have +1 for O and -1 for X instead of 1 and 2, in that way you can sum up all 3 rows (in a loop), all 3 columns (in a loop) and both diagonals and if they sum to +3 O has a winning line, -3 means X has a winning line. You can exit the test early if you find a win for either player.

More sophisticated would be to use a bitboard but Alvaro will probably be along in a minute to boggle your mind with that idea ;)

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

### #3Giallanon  Members

1819
Like
10Likes
Like

Posted 14 August 2014 - 06:08 AM

POPULAR

For something as simple as this,I would go with simple brute force. After all, you only have to check 3 rows, 3 cols and 2 diagonals

### #4Random2323  Members

230
Like
0Likes
Like

Posted 14 August 2014 - 07:05 AM

Do it in the way that is easiest for you, the reader of the code, to understand.

Although a good idea would be to have +1 for O and -1 for X instead of 1 and 2, in that way you can sum up all 3 rows (in a loop), all 3 columns (in a loop) and both diagonals and if they sum to +3 O has a winning line, -3 means X has a winning line. You can exit the test early if you find a win for either player.

More sophisticated would be to use a bitboard but Alvaro will probably be along in a minute to boggle your mind with that idea ;)

Yeah thanks for the tip man and I wonder who Alvaro is and what he has to say haha !

For something as simple as this,I would go with simple brute force. After all, you only have to check 3 rows, 3 cols and 2 diagonals

Yeah that's what I thought first but I just wanted to know what other more formal methods there are out there.

Edited by AspiringDev, 14 August 2014 - 07:15 AM.

### #5Álvaro  Members

20270
Like
7Likes
Like

Posted 14 August 2014 - 07:19 AM

POPULAR

More sophisticated would be to use a bitboard but Alvaro will probably be along in a minute to boggle your mind with that idea ;)

Coming through! But not with bitboards. For tic-tac-toe, I posted a much better solution a couple of years ago.

### #6 slalrbalr   Banned

2006
Like
2Likes
Like

Posted 14 August 2014 - 07:22 AM

I was just typing this, but now it's pointless: (or maybe not )

There aren't that many solutions, and the best way to represent one solution would be as 3x3 1-bit values. 3x3 = 9 bits, which easily fits in a short unsigned int (16-bits).

You can also represent your existing values like this, by using  two short unsigned int - one for O/X stored in the 9 slots, and a mask where 0 means that the slot wasn't filled yet, and 1 means that the slot was filled with the value from the O/X int. As players fill in the slots, you set the bits (using logical or) accordingly, and you can then detect if the game ends by checking if the lower 9 bits in the mask are set. If they are, you just compare the O/X int against a list of solutions (ints).

Reference: http://xkcd.com/832/

Edited by tonemgub, 14 August 2014 - 07:32 AM.

### #7Random2323  Members

230
Like
0Likes
Like

Posted 14 August 2014 - 07:30 AM

More sophisticated would be to use a bitboard but Alvaro will probably be along in a minute to boggle your mind with that idea ;)

Coming through! But not with bitboards. For tic-tac-toe, I posted a much better solution a couple of years ago.

WOW I'm left speechless. I hope I will implement it the right way ! Can't thank you enough !

I was just typing this, but now it's pointless: (or maybe not )

There aren't that many solutions, and the best way to represent one solution would be as 3x3 1-bit values. 3x3 = 9 bits, which easily fits in a short unsigned int (16-bits).

You can also represent your existing values like this, by using  two short unsigned int - one for O/X stored in the 9 slots, and a mask where 0 means that the slot wasn't filled yet, and 1 means that the slot was filled with the value from the O/X int. As players fill in the slots, you set the bits (using logical or) accordingly, and you can then detect if the game ends by checking if the lower 9 bits in the mask are set. If they are, you just compare the O/X int against a list of solutions (ints).

Very helpful explanation my friend. Really I couldn't think that a problem of this kind could have a more sophisticated solution than the normal traversal methods and brute forcing .

Again thanks both of you !

### #8Aphton  Members

356
Like
1Likes
Like

Posted 14 August 2014 - 01:53 PM

A simple brute-force optimization that came to mind when reading the title was:

(

1,2,3,
4,5,6,
7,8,9

)

For each cell, you can perform 3 checks: Horizontal (H), Vertical (V) and Diagonal (D(D1, D2))

But not all checks are needed for each cell, so lets see:

Cell 1: H, V, D1
Cell 2: V
Cell 3: V, D2
Cell 4: H
Cell 5: -
Cell 6: -
Cell 7: H
Cell 8: -
Cell 9: -

In case its not clear:
Cell 2: H is not needed because its covered by Cell1-H and D is simply not possible

Cell 5: H is covered by Cell4-H, Diagonals are covered by Cell1-D1 and Cell3-D2 and V is covered by Cell2-V

So this leaves you with 3x H, 3x V and 2x D checks ~ 8x Checks in total, which is much less then 36x Checks

Ofc the other solutions are much more elegant (referring to the one suggested at #5)

Edit: Oh and ofc, the traversal itself could look like this:

// Horizontal
for (int i = 0; i < 3; i++)
... field[(pos.x + i) % 3, pos.y] ...

// Vertical
for (int i = 0; i < 3; i++)
... field[pos.x, (pos.y + i) % 3] ...

// Diag 1
for (int i = 0; i < 3; i++)
... field[(pos.x + i) % 3, (pos.y + i) % 3] ...

// Diag 2
for (int i = 0; i < 3; i++)
... field[(pos.x - i) % 3, (pos.y + i) % 3] ...

Im not sure about whether C++ % (mod) handles negative numbers mathematically correctly..

Edited by Aphton, 14 August 2014 - 02:30 PM.

### #9Servant of the Lord  Members

33572
Like
1Likes
Like

Posted 14 August 2014 - 04:39 PM

Im not sure about whether C++ % (mod) handles negative numbers mathematically correctly..

After a four-hour debugging session a year or two ago, the answer to that is: No, it does not.

It's perfectly fine to abbreviate my username to 'Servant' or 'SotL' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames -

### #10rip-off  Moderators

10730
Like
3Likes
Like

Posted 14 August 2014 - 04:40 PM

Here is a version which, while still containing a few "magic" numbers, I think they can be more readily be deciphered than Álvaro's linked version due to the names involved. I also think the logic of the algorithm is more obvious than Álvaro's neat little trick:

enum Piece {
None,
X,
O
};

typedef Piece Board[3][3];

struct VictoryCondition {
int startIndex;
int stride;

int index(int i) const {
return startIndex + (i * stride);
}
};

const VictoryCondition possibleVictories[] = {
{0, 1}, {3, 1}, {6, 1},
{0, 3}, {1, 3}, {2, 3},
{0, 4}, {2, 2}
};

Piece winner(Board board) {
Piece *pointer = &board[0][0];
for(VictoryCondition v : possibleVictories) {
Piece possibleVictor = pointer[v.index(0)];
if(possibleVictor != None && possibleVictor == pointer[v.index(1)] && possibleVictor == pointer[v.index(2)]) {
return possibleVictor;
}
}
return None;
}


I wouldn't say this is the "best", personally I think the tedious but obvious set of loops is probably the way to go without a compelling reason otherwise.

Edited by rip-off, 14 August 2014 - 04:41 PM.

### #11Álvaro  Members

20270
Like
5Likes
Like

Posted 14 August 2014 - 08:16 PM

POPULAR

With bitboards, it would look like this (remember you only need to check the side that just moved):
// The assignment of bit numbers to squares goes like this:
// 8 7 6
// 5 4 3
// 2 1 0

bool three_in_a_line(unsigned x) {
if (x & (x>>1) & (x>>2) & 0111)
return true;
if (x & (x>>3) & (x>>6) & 0007)
return true;
if (x & (x>>4) & (x>>8) & 0001)
return true;
if (x & (x>>2) & (x>>4) & 0004)
return true;
return false;
}

Disclaimer: I didn't test the code.

### #12frob  Moderators

41391
Like
1Likes
Like

Posted 15 August 2014 - 12:49 AM

More sophisticated would be to use a bitboard but Alvaro will probably be along in a minute to boggle your mind with that idea ;)

Coming through! But not with bitboards. For tic-tac-toe, I posted a much better solution a couple of years ago.

As the game only has 8 solutions, storing them as bit flags seems quite reasonable. I like it.

Check out my book, Game Development with Unity, aimed at beginners who want to build fun games fast.

Also check out my personal website at bryanwagstaff.com, where I occasionally write about assorted stuff.

### #13Jason Z  Members

6417
Like
2Likes
Like

Posted 16 August 2014 - 09:53 AM

While the solutions posted here are really interesting, is it really the best thing to tell a beginner to use low level bit operations to check if someone wins at tic-tac-toe?  I would recommend just iterating through the board, checking each of the possibilities (as already mentioned, 3 horizontal, 3 vertical, and two diagonal).  Once that is working, then you can start to try to optimize the solution (i.e. create separate functions for each type of check, build incremental lists of winning moves, or whatever).

However, all of those are just for learning - I can't believe that a check that is done once for each of the 9 moves in a game is really a candidate for doing abstract optimizations...

Jason Zink :: DirectX MVP

Direct3D 11 engine on CodePlex: Hieroglyph 3

Games: Lunar Rift

### #14Álvaro  Members

20270
Like
1Likes
Like

Posted 17 August 2014 - 05:08 AM

While the solutions posted here are really interesting, is it really the best thing to tell a beginner to use low level bit operations to check if someone wins at tic-tac-toe?  I would recommend just iterating through the board, checking each of the possibilities (as already mentioned, 3 horizontal, 3 vertical, and two diagonal).  Once that is working, then you can start to try to optimize the solution (i.e. create separate functions for each type of check, build incremental lists of winning moves, or whatever).

However, all of those are just for learning - I can't believe that a check that is done once for each of the 9 moves in a game is really a candidate for doing abstract optimizations...

I have written code for a lot of board games. The first thing I do is come up with a board representation, a move representation, and functions to make moves, undo moves, generate moves and check for end-of-game conditions.

If you are writing a GUI where these things will only be needed once per move in a game, you normally don't have to think about it too hard, and any naive implementation will do.

But if you are writing any type of AI, you are going to have to consider gazillions of moves internally, whether you are using minimax, MCTS or something else. The performance of those basic routines really does matter, and there are clever implementations to be found for pretty much every game I can think of.

Tic-tac-toe is a learning tool, and it's a good opportunity to learn how to think of these clever implementations as well.

EDIT: One more thing: This is not the "For Beginners" forum. The thread I linked to was in "For Beginners", and I was reluctant to describe the fancy bit-manipulation method there.

Edited by Álvaro, 17 August 2014 - 08:01 AM.

### #15Anthony Serrano  Members

2926
Like
1Likes
Like

Posted 17 August 2014 - 12:13 PM

For something as simple as this,I would go with simple brute force. After all, you only have to check 3 rows, 3 cols and 2 diagonals

One simple optimization of that is that, if you're checking after every move, you only need to check the winning patterns that involve the cell just played, which reduces it to checking just 1 row, 1 column, and 0 to 2 diagonals after every move.

### #16Jason Z  Members

6417
Like
1Likes
Like

Posted 19 August 2014 - 01:58 PM

While the solutions posted here are really interesting, is it really the best thing to tell a beginner to use low level bit operations to check if someone wins at tic-tac-toe?  I would recommend just iterating through the board, checking each of the possibilities (as already mentioned, 3 horizontal, 3 vertical, and two diagonal).  Once that is working, then you can start to try to optimize the solution (i.e. create separate functions for each type of check, build incremental lists of winning moves, or whatever).

However, all of those are just for learning - I can't believe that a check that is done once for each of the 9 moves in a game is really a candidate for doing abstract optimizations...

I have written code for a lot of board games. The first thing I do is come up with a board representation, a move representation, and functions to make moves, undo moves, generate moves and check for end-of-game conditions.

If you are writing a GUI where these things will only be needed once per move in a game, you normally don't have to think about it too hard, and any naive implementation will do.

But if you are writing any type of AI, you are going to have to consider gazillions of moves internally, whether you are using minimax, MCTS or something else. The performance of those basic routines really does matter, and there are clever implementations to be found for pretty much every game I can think of.

Tic-tac-toe is a learning tool, and it's a good opportunity to learn how to think of these clever implementations as well.

EDIT: One more thing: This is not the "For Beginners" forum. The thread I linked to was in "For Beginners", and I was reluctant to describe the fancy bit-manipulation method there.

That is a completely valid point - I was just making an observation based on the nature of the question from the OP.  Like I said, you solutions are really interesting, and they may just be what the OP was asking for.  I just thought for the game at hand it was slightly more than what was required.

Jason Zink :: DirectX MVP

Direct3D 11 engine on CodePlex: Hieroglyph 3

Games: Lunar Rift

### #17Random2323  Members

230
Like
0Likes
Like

Posted 20 August 2014 - 02:33 AM

Well I started the thread to check if there are some more efficient and somewhat complicated methods to approach this particular problem so I can broaden my horizons about efficient problem solving. I'm quite ashamed to say that the truth is I had a hard time understanding most of the posts here but they were good head scratchers for sure despite my lack of knowledge on bitwise operations. I used the usual check with loops and the game works perfectly now so at least I had that. Probably I brought more hassle to you who post all these great methods and explanations and I feel kinda bad that I didn't manage to implement them or even understand them fully but you helped me by showing me interesting things I could never have thought by myself. So...sorry if my question bothered you too much and brought the work on you to explain things but at the same time thank you for being awesome with your  programming magic you showed me !

### #18 slalrbalr   Banned

2006
Like
1Likes
Like

Posted 20 August 2014 - 05:13 AM

So...sorry if my question bothered you too much and brought the work on you to explain things but at the same time thank you for being awesome with your programming magic you showed me !

Don't worry about it... We enjoy bragging about our programming magic skills...

The bitwise operations are basically the same as brute force anyway - the only difference is that they work at the bit-level.

### #19Lactose  GDNet+

9653
Like
1Likes
Like

Posted 20 August 2014 - 05:24 AM

Also, even if you don't understand it all right now, it can still be used as a reference later on.

And it might help others who just lurk or happen to google the same problem.

Hello to all my stalkers.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.