Skip to content

Instantly share code, notes, and snippets.

@nitsanavni
Last active May 21, 2019 19:32
Show Gist options
  • Save nitsanavni/04f41226bd7923f1714b4b921a4eab26 to your computer and use it in GitHub Desktop.
Save nitsanavni/04f41226bd7923f1714b4b921a4eab26 to your computer and use it in GitHub Desktop.
subgroups exercise using recursion
const _ = require("lodash");
function subgroups(elements) {
if (elements.length == 1) {
return [elements];
}
const drop = subgroups(_.drop(elements));
const first = _.take(elements);
const combined = [..._.map(drop, (i) => [...i, ...first]), ...[...drop, first]];
return combined;
}
describe("subgroups", () => {
_(_.range(2, 6))
.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) - 1));
it("should unique", () => expect(_.uniq(res).length).toBe((1 << inputElements.length) - 1));
});
});
});
@rommguy
Copy link

rommguy commented May 21, 2019

Nice! that's my solution too, recursion

I also started with the same stop condition as you: length === 1, but after I finished writing and started thinking that maybe the empty group should also be returned. Than I saw that if I change the stop condition to return the empty group, it also simplifies the combined calculation

My solution (and no lodash :))-

function subgroups(elements) {
    if (elements.length == 0) {
        return [[]];
    }

    const [first, ...rest] = elements
    const restSubgroups = subgroups(rest)
    const firstSubgroups =  restSubgroups.map(subgroup => [first, ...subgroup]) 

    return [...firstSubgroups, ...restSubgroups];
}

@nitsanavni
Copy link
Author

cool :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment