为何判断3x3数组首行全相等的两种表达式均有效?
Hey there! Let's unpack why both your solution and your friend's seemingly redundant one work perfectly for checking if all elements in the first row of your tictactoe 3x3 int array are equal.
First, let's assume what your two expressions might look like (common approaches for this check):
- Your concise solution:
tictactoe[0][0] == tictactoe[0][1] && tictactoe[0][0] == tictactoe[0][2] - Your friend's "redundant" solution:
tictactoe[0][0] == tictactoe[0][1] && tictactoe[0][1] == tictactoe[0][2] && tictactoe[0][0] == tictactoe[0][2]
Here's the key logic at play: If a == b and b == c, then by transitivity, a must equal c. That third check in your friend's code is technically unnecessary—but it doesn't break the expression. Let's walk through different scenarios to confirm:
- All elements are equal: Say the first row is
[5,5,5]. Both expressions evaluate totrue—yours checks 55 and 55; your friend's adds an extra 5==5, which is still true. - Two elements equal, one different: If the row is
[5,5,7], your expression fails at5==7; your friend's fails at5==7(and even if short-circuit evaluation didn't skip the third check,5==7is still false). - No elements equal: For
[5,7,9], your expression fails at the first check5==7; your friend's also fails at that first check, and the rest of the conditions never run thanks to short-circuit&&behavior.
The "redundant" condition doesn't make the expression wrong—it just does an extra comparison that doesn't change the final outcome. Logically, both expressions are fully equivalent for verifying that all three elements in the first row are identical.
内容的提问来源于stack exchange,提问作者Garrison Davis

