问题描述
我一直在挣扎了很长一段时间这个问题。这是这个答案的后续问题(How来划分玩家x个到2队任意多次,不同的每一次?)。
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?).
所以,我的球员x个,并为每个我给 1 LT;< ñ
屏蔽值。通过使用这些面具,我可以很容易地形成2个玩家在每队比赛。现在,如果玩家的总数是5,一个可能的对手可能是这样的:
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
或6名球员也可能是这样的:
or with 6 players it could look like this:
100010 team a
001001 team b
-------------
000100 player resting
010000 player resting
问结果
我怎样才能获得通过对比队和B队一起口罩休息的那些球员? (我是一个总的按位小白所以code例子是很好AP preciated)
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)
感谢
推荐答案
XOR 价值A队和B的:
var resting = a ^ b;
然后休息的球员将通过 0
标记,即:
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;
}
下面就是活生生的例子:(在Java中,没有JavaScript的,但是这不是问题)
Here's live example: http://ideone.com/Kb3XJ (in Java, not JavaScript, but that's not the issue)
这篇关于如何使用位运算符来返回有0位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!