Skip to content

Commit

Permalink
BitSet.cardinality() - courtesy Hacker's Delight
Browse files Browse the repository at this point in the history
  • Loading branch information
monmohan committed Nov 23, 2013
1 parent 0d34344 commit c756ea1
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
19 changes: 19 additions & 0 deletions lib/BitSet.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,25 @@

};

/**
* Return the number of bits set to true in this
* BitSet
* Courtesy Hacker's Delight 5.1
*/
BitSet.prototype.cardinality = function () {
return this._words.reduce(function (sum, w) {
w = w - ((w >>> 1) & 0x55555555);
w = (w & 0x33333333) + ((w >>> 2) & 0x33333333);
w = (w + (w >>> 4)) & 0x0f0f0f0f;
w = w + (w >>> 8);
w = w + (w >>> 16);
return sum + (w & 0x3F);

}, 0);

};


BitSet.prototype.size = function () {
return this._wordsUsed * BITS_PER_WORD;
};
Expand Down
19 changes: 19 additions & 0 deletions tests/TestBitSet.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,27 @@ var BitSet = require('../lib/BitSet.js'), assert = require('assert'), fs = requi

}

function testCardinality() {
var bs = new BitSet();
bs.set(10);
bs.set(2);
assert.equal(bs.cardinality(), 2, 'wrong cardinality');
bs = new BitSet(1000);
for (var i = 0; i < 20; i++) {
bs.set(i * 10);
}
assert.equal(bs.cardinality(), 20, 'wrong cardinality');
//clear a few
for (i = 0; i < 20; i++) {
bs.clear(i * 20);
}
assert.equal(bs.cardinality(), 10, 'wrong cardinality');

}

testBasic();
testLargeBitSet();
testCardinality();


})();

0 comments on commit c756ea1

Please sign in to comment.