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->turnsgoes through consecutive values, its last bits switches between 0 and 1 on each iteration. As the result,game->turns & 1goes 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.Note how the sequence goes 0-1-0-1-0-1 when
game->computer_firstisfalse, and 1-0-1-0-1-0 whengame->computer_firstistrue.To convert this snippet to Java, compare the result of
game.turns & 1with):