gator - 1 year ago 136
C++ Question

# Four-way equivalence

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`
will be one of three values (0 for neither X or O, 1 for X, 2 for O), it would need only changing the value of O to 4 or something impossible to achieve with three 1s, 0s, or combinations thereof. But it lacks finesse.

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download