gator - 8 months ago 83

C++ Question

How do I check the equality between four variables? This is for a 3D tic-tac-toe game.

`if (b[0][0] == b[1][0] == b[2][0] == p) { line += 1; }`

This doesn't work as equivalent is left-to-right. I don't want to do either of the below:

`if (b[0][0] == p && b[1][0] == p && b[2][0] == p) { line += 1; }`

if ((b[0][0] == b[1][0]) && (b[1][0] == b[2][0]) && (b[2][0] == p)) { line += 1; }

All variables are integers, as I know with bools I can just use &&. Is there a better way? I considered:

`if ((b[0][0] + b[1][0] + b[2][0]) == (3 * p)) { line += 1; }`

Since

`p`

Answer

Now that you've mentioned tic-tac-toe, things change a bit. Ultimately you'll be checking each column for the same value and each row for the same value. That doesn't require a long `if ... else if...`

ladder. Instead, write a function to check a row:

```
bool row_matches(board b, int row, int value) {
for (int col = 0; col < 3; ++col)
if (b[row][col] != value)
return false;
return true;
}
```

and write a similar function for columns. Diagonals are even simpler.

Source (Stackoverflow)