【问题标题】:Javascript Mask ComputingJavascript掩码计算
【发布时间】:2015-03-30 05:19:23
【问题描述】:

所以我知道我的问题是关于掩蔽。我看到了 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 技能。

还有这种方法叫什么?

【问题讨论】:

标签: javascript algorithm


【解决方案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");
}

【讨论】:

    【解决方案2】:

    假设您有 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 ) );
    

    【讨论】:

      【解决方案3】:

      如果您想要一种简单的方法,只需屏蔽位并将其与数字进行比较:

      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;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-06
        • 2014-10-26
        • 1970-01-01
        • 2012-10-06
        • 2012-12-28
        相关资源
        最近更新 更多