所以我明白我的问题是关于掩盖。我看到了javascript here屏蔽的文档。
所以我试过了:
var PEN = 1;
var CHAIR = 2;
var TABLE = 4;
> PEN | CHAIR
3
但是,如果我拥有3
怎么能从这个数字中获得我所拥有的东西呢?
说,我有以下常数:
1 | 2 | 4
这些数字对应于某种东西。
让我们说:1是笔,2是椅子,4是桌子。
的可能性:
If I have the #1 it means I have a pen but NO chair and table.
If I have the #2 it means I have a chair but NO pen and table.
If I have the #4 it means I have a table but NO pen and chair.
If I have the #3 it means I have a pen and a chair but NO table.
If I have the #6 it means I have a chair, a table but NO pen.
If I have the #7 it means I have a pen, a chair and a table.
问题:现在说我所知道的就是数字6.我如何以编程方式破译6表示2和4或者我有椅子和桌子?
对不起,这也让我很困惑。我试图将游戏的技能列表算法重新实现为javascript。如果我有6则意味着我拥有第2和第3技能但不是第1技能。
这种方法又叫什么?
答案 0 :(得分:1)
这看起来更像是找到总计目标值的元素的问题:
var elementsUsedInSum = function (arr, sum) {
var curr_sum = arr[0], start = 0, i;
for (i = 1; i <= arr.length; i++)
{
while (curr_sum > sum && start < i-1)
{
curr_sum = curr_sum - arr[start];
start += 1;
}
if (curr_sum === sum)
{
console.log ("Elements from " + start + " to " + i-1 + " found.");
}
// Add this element to curr_sum
if (i < n)
curr_sum = curr_sum + arr[i];
}
console.log ("Combination not possible");
}
答案 1 :(得分:1)
假设您有5种技能...... A,B,C,D和E.您可以将这些技能编码为整数的第一,第二,第三,第四和第五位。
所以,如果球员技能为0b00001000 ......这意味着他有第四技能。
现在,
// No skill
var skill = 0;
// add skill B... which means set second bit to 1.
skill = skill | ( 1 << 1 );
// add skill A
skill = skill | ( 1 << 0 );
//check for skill B,
var hasSkillB = ( ( skill & ( 1 << 1 ) ) > 0 );
// Remove skill B
skill = skill & ( ~( 1 << 1 ) );
答案 2 :(得分:0)
如果您想要一种简单的方法,只需屏蔽这些位并将其与数字进行比较:
var FLAG_A = 1; // 0001 - PEN
var FLAG_B = 2; // 0010 - CHAIR
var FLAG_C = 4; // 0100 - TABLE
var PEN;
var CHAIR;
var TABLE;
n = 3; //Input number
if (n & FLAG_A) {
PEN = true;
} else {
PEN = false;
}
if (n & FLAG_B) {
CHAIR = true;
} else {
CHAIR = false;
}
if (n & FLAG_C) {
TABLE = true;
} else {
TABLE = false;
}