Skip to content

Instantly share code, notes, and snippets.

@nitsanavni
Last active May 21, 2019 19:27
Show Gist options
  • Save nitsanavni/7a6a6af02f9a5862e42c8e2e587a3860 to your computer and use it in GitHub Desktop.
Save nitsanavni/7a6a6af02f9a5862e42c8e2e587a3860 to your computer and use it in GitHub Desktop.
subgroups exercise using bit ops
const _ = require("lodash");
function subgroups(elements) {
const bits = _.range(32);
const indices = (i) =>
_(bits)
.map((b) => (1 + b) * (0x1 & (i >> b)))
.compact() // only leave the `1`s
.map((b) => b - 1)
.value();
return _(_.range(1 << elements.length))
.map((i) => _.at(elements, indices(i)))
.value();
}
describe("subgroups", () => {
_(_.range(2, 9))
.map((n) => _.range(1, n))
.each((inputElements) => {
describe(`${inputElements}`, () => {
let res;
beforeAll(() => (res = subgroups(inputElements)));
it("should 2^n", () => expect(res.length).toBe(1 << inputElements.length));
it("should unique", () => expect(_.uniq(res).length).toBe(1 << inputElements.length));
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment