Created
August 20, 2020 20:09
-
-
Save wusher/d367399f175a34b826ae9852f5bf58e3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { expect } from "chai"; | |
function buildCombinations(start: string, pieces: string[]): string[] { | |
if (pieces.length < 1) { | |
return [start]; | |
} | |
const allCombinations: string[][] = pieces.map((newStart) => { | |
let remaining = [...pieces]; | |
remaining.splice(remaining.indexOf(newStart), 1); | |
const combs = buildCombinations(newStart, remaining); | |
return combs.map((x) => start + x); | |
}); | |
const results: string[] = []; | |
allCombinations.forEach((row: string[]) => { | |
row.forEach((x) => results.push(x)); | |
}); | |
return results; | |
} | |
function combinations(num: number): number[] { | |
const tokens = String(num).split(""); | |
const results = buildCombinations("", tokens); | |
return results.map((x) => Number(x)); | |
} | |
describe("combinations", () => { | |
it("returns a single item array for numbers less than 10", () => { | |
expect(combinations(5)).to.deep.equal([5]); | |
}); | |
it("returns all combinations of 2 digit numbers", () => { | |
expect(combinations(42)).to.deep.equal([42, 24]); | |
}); | |
it("returns all combinations of 3 digit numbers", () => { | |
expect(combinations(421)).to.deep.equal([421, 412, 241, 214, 142, 124]); | |
}); | |
it("example passes", () => { | |
expect(combinations(123)).to.deep.equal([123, 132, 213, 231, 312, 321]); | |
}); | |
it("returns all combinations of 3 digit numbers with duplicates", () => { | |
expect(combinations(424)).to.deep.equal([424, 442, 244, 244, 424, 442]); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
combinations | |
✓ returns a single item array for numbers less than 10 | |
✓ returns all combinations of 2 digit numbers | |
✓ returns all combinations of 3 digit numbers | |
✓ example passes | |
✓ returns all combinations of 3 digit numbers with duplicates |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment