0

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

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

3 Comments

You're snippet works OK if the players resting are NOT the last bits. See here: jsfiddle.net/Mm4MM/1. Do you know the fix?
That's because 011011 is equal to 11011. You'll have to store the total number of players in separate variable, and then change for-loop condition, from resting != 0 to i <= totalPlayers - take a look at my edit. JSFiddle live example
Cool, that was a simple fix I would have not see. Thank you!
0

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.