I'm trying to understand this snippet
for (; game->boxes_left > 0; game->turns++)
{
if ( (game->turns & 1) ^ game->computer_first )
game->human_move();
else
game->computer_move();
}
as inf game->turns is an integer, and it has increasing value , and game->comp_first is a boolean, Will anyone please tell me how if ( (game->turns & 1) ^ game->computer_first ) return it's 1 (true) or 0 (false) ?
because what I understand & is bitwise operator and when turns & 1 it will always return 0 , as turns is an increasing value, what is the function of (game->turns & 1) in this if statement? is there any way to write this snippet in java. Thanks in advance
As game->turns goes through consecutive values, its last bits switches between 0 and 1 on each iteration. As the result, game->turns & 1 goes between 0 and 1 as well. XOR-ing the result with a bool gives you the same value if bool is false, and an inverted value if bool is true.
game->turns Last bit XOR 0 XOR 1
----------- -------- ----- -----
0 0 0 1
1 1 1 0
2 0 0 1
3 1 1 0
4 0 0 1
5 1 1 0
Note how the sequence goes 0-1-0-1-0-1 when game->computer_first is false, and 1-0-1-0-1-0 when game->computer_first is true.
To convert this snippet to Java, compare the result of game.turns & 1 with ):
if (((game.turns & 1) != 0) ^ game->computer_first) ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With