How to use bitwise operators to return bits that h

2019-09-12 01:45发布

问题:

I've been struggling for quite a long time on this problem. This is a follow-up question on this answer (How to divide x number of players into 2 teams randomly multiple times, differently every time?).

So, I have x number of players, and for each I give 1 << n mask value. By using those masks I can easily form a match with 2 players in each team. Now, if total number of players is 5, one possible match could be like this:

01100 team a
00011 team b
------------
10000 player resting

or with 6 players it could look like this:

100010 team a
001001 team b
-------------
000100 player resting
010000 player resting

Question
How can I get those resting players by comparing team a and team b masks together? (I'm a total bitwise noob so code examples are well appreciated)

Thanks

回答1:

Do XOR on value of team A and B:

var resting = a ^ b;

Then resting players will be marked by 0, i.e:

100010 team a
001001 team b
-------------
101011 players resting

Finally, iterate through each bit of the result:

var totalPlayers = 6;

for (var i = 1; i <= totalPlayers; i++) {

   if ((resting & 1) === 0) {
       console.log("Player #" + i + " is resting.");
   }

   resting >>>= 1;
}

Here's live example: http://ideone.com/Kb3XJ (in Java, not JavaScript, but that's not the issue)



回答2:

You can bitwise OR them together then NOT it to get all the resting players. You would then have to go bit by bit to get the separate resting players.

100010 
001001
------OR
101011 #all players playing
------NOT
010100 #all players not playing