Created
December 9, 2021 16:29
-
-
Save pengx17/ebc687d7cf6f59cdb226e8b9de4e2bd9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| function permutate(arr = []) { | |
| let res = []; | |
| if (arr.length === 1) { | |
| return [arr]; | |
| } | |
| for (let i = 0; i < arr.length; i++) { | |
| let c = arr[i]; | |
| let rest = arr.slice(); | |
| rest.splice(i, 1); | |
| permutate(rest).forEach((t) => res.push([c, ...t])); | |
| } | |
| return res; | |
| } | |
| let allPermutations = permutate("abcdefg".split("")); | |
| function seqToNum(seq) { | |
| function p(...ns) { | |
| return ns.reduce((a, b) => [...a, seq[b]], []); | |
| } | |
| const c0 = p(0, 1, 2, 4, 5, 6); | |
| const c1 = p(2, 5); | |
| const c2 = p(0, 2, 3, 4, 6); | |
| const c3 = p(0, 2, 3, 5, 6); | |
| const c4 = p(1, 2, 3, 5); | |
| const c5 = p(0, 1, 3, 5, 6); | |
| const c6 = p(0, 1, 3, 4, 5, 6); | |
| const c7 = p(0, 2, 5); | |
| const c8 = p(0, 1, 2, 3, 4, 5, 6); | |
| const c9 = p(0, 1, 2, 3, 5, 6); | |
| return [c0, c1, c2, c3, c4, c5, c6, c7, c8, c9].map((seq) => { | |
| seq.sort(); | |
| return seq.join(""); | |
| }); | |
| } | |
| const sequences = allPermutations.map(seqToNum); | |
| // 0: 1: 2: 3: 4: | |
| // aaaa .... aaaa aaaa .... | |
| // b c . c . c . c b c | |
| // b c . c . c . c b c | |
| // .... .... dddd dddd dddd | |
| // e f . f e . . f . f | |
| // e f . f e . . f . f | |
| // gggg .... gggg gggg .... | |
| // 5: 6: 7: 8: 9: | |
| // aaaa aaaa aaaa aaaa aaaa | |
| // b . b . . c b c b c | |
| // b . b . . c b c b c | |
| // dddd dddd .... dddd dddd | |
| // . f e f . f e f . f | |
| // . f e f . f e f . f | |
| // gggg gggg .... gggg gggg | |
| function sortStr(str) { | |
| return str.split("").sort().join(""); | |
| } | |
| function findTheOne(tenOfThem) { | |
| tenOfThem = tenOfThem.map(sortStr); | |
| return sequences.find((candidates) => { | |
| return candidates.every((s) => tenOfThem.includes(s)); | |
| }); | |
| } | |
| function run(input = "") { | |
| const lines = input | |
| .split("\n") | |
| .filter(Boolean) | |
| .map((line) => { | |
| const [fore, back] = line.split("|"); | |
| return [fore.trim().split(" "), back.trim().split(" ")]; | |
| }); | |
| return lines.reduce((acc, [fore, back]) => { | |
| const theOne = findTheOne(fore); | |
| back = back.map(sortStr).map(b => theOne.findIndex(o => o === b)) | |
| back = parseInt(back.join('')); | |
| return acc + back; | |
| }, 0); | |
| } | |
| console.log(run(raw)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment