0

So I understand that my question is about masking. I saw the documentation of masking for javascript here.

so I tried:

var PEN = 1;
var CHAIR = 2;
var TABLE = 4;

> PEN | CHAIR
3

But what if what I have is 3 how do I get what I have from that number alone?

Original Question

Say, I have the following constant numbers:

1 | 2 | 4

These numbers corresponds to a something.

Let us say: 1 is a pen, 2 is a chair and 4 is a table.

Possibilities:

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.

Question: Now say all I know about is the number 6. How do I programatically decipher that 6 means 2 and 4 or I have a chair and a table?

Sorry, this is also confusing me. I'm trying to reimplement a skills list algorithm for a game to javascript. Where if I have 6 it means I have the 2nd and 3rd skill but not the 1st skill.

Also what is this approach called?

majidarif
  • 18,694
  • 16
  • 88
  • 133

3 Answers3

1

This looks more like a problem of finding elements summing up to the target value:

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");
}
nitishagar
  • 9,038
  • 3
  • 28
  • 40
1

Lets say you have 5 skills... A, B, C, D and E. You can encode these skills as first, second, third, fourth and fifth bit of an integer.

So, if a players skill is 0b00001000... that means he has 4th skill.

Now,

// 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 ) );
sarveshseri
  • 13,738
  • 28
  • 47
0

If you want an easy way to do it just mask the bits and compare it with the number:

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