Skip to content

Instantly share code, notes, and snippets.

@102
Last active November 4, 2020 04:46
Show Gist options
  • Save 102/39942334287ea09ecb2f3347853c0a8b to your computer and use it in GitHub Desktop.
Save 102/39942334287ea09ecb2f3347853c0a8b to your computer and use it in GitHub Desktop.
let countBits = (x) => x.toString(2).replace(/0/g, "").length;
let sortBits = (x) => [...x].sort((a, b) => countBits(a) - countBits(b));
module.exports.sortBits = sortBits;
// this one is much faster than the naive solution, but it does not work
// for numbers bigger than 32 bits, i.e. 0b11111111111111111111111111111111
// or 4294967295 is the biggest number this function can correctly work with
let countBits = (i) => {
let count = 0;
i = i - ((i >> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
i = (i + (i >> 4)) & 0x0f0f0f0f;
i = i + (i >> 8);
i = i + (i >> 16);
count += i & 0x3f;
return count;
};
let sortBits = (x) => [...x].sort((a, b) => countBits(a) - countBits(b));
module.exports.sortBits = sortBits;
const sortBits0 = require("./naive").sortBits;
const sortBits1 = require("./pretend_that_i_have_cs_degree").sortBits;
const iterations = 1000000;
console.time("Function #2");
for (let i = 0; i < iterations; i++) {
sortBits1([4124515, 1231251, 123, 1412, 56134, 222]);
}
console.timeEnd("Function #2");
console.time("Function #1");
for (let i = 0; i < iterations; i++) {
sortBits0([4124515, 1231251, 123, 1412, 56134, 222]);
}
console.timeEnd("Function #1");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment