|
| 1 | +import { timePart1, timePart2 } from "../../utils/time-part"; |
| 2 | + |
| 3 | +const parseInput = (input: string) => { |
| 4 | + const [availableTowels, designs] = input.split("\n\n"); |
| 5 | + |
| 6 | + return { |
| 7 | + availableTowels: availableTowels.split(", "), |
| 8 | + designs: designs.split("\n"), |
| 9 | + }; |
| 10 | +}; |
| 11 | + |
| 12 | +export const part1 = timePart1((input: string) => { |
| 13 | + const { availableTowels, designs } = parseInput(input); |
| 14 | + let possibleDesigns = 0; |
| 15 | + |
| 16 | + for (const design of designs) { |
| 17 | + let queue: Array<{ remaining: string }> = []; |
| 18 | + |
| 19 | + for (const towel of availableTowels) { |
| 20 | + if (design.indexOf(towel) === 0) { |
| 21 | + queue.push({ remaining: design.substring(towel.length) }); |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + while (queue.length) { |
| 26 | + queue.sort((a, b) => a.remaining.length - b.remaining.length); |
| 27 | + const entry = queue.shift()!; |
| 28 | + |
| 29 | + for (const towel of availableTowels) { |
| 30 | + if (entry.remaining.indexOf(towel) === 0) { |
| 31 | + if (entry.remaining.length === towel.length) { |
| 32 | + possibleDesigns++; |
| 33 | + queue = []; |
| 34 | + break; |
| 35 | + } |
| 36 | + |
| 37 | + queue.push({ remaining: entry.remaining.substring(towel.length) }); |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + return possibleDesigns; |
| 44 | +}); |
| 45 | + |
| 46 | +export const part2 = timePart2((input: string) => { |
| 47 | + const { availableTowels, designs } = parseInput(input); |
| 48 | + let possibleDesigns = 0; |
| 49 | + const canBeCompleted = new Map<string, number>(); |
| 50 | + |
| 51 | + const countTowelVariants = (remaining: string) => { |
| 52 | + if (canBeCompleted.has(remaining)) { |
| 53 | + return canBeCompleted.get(remaining)!; |
| 54 | + } |
| 55 | + |
| 56 | + let variants = 0; |
| 57 | + |
| 58 | + for (const towel of availableTowels) { |
| 59 | + if (remaining.indexOf(towel) === 0) { |
| 60 | + if (remaining.length === towel.length) { |
| 61 | + variants++; |
| 62 | + continue; |
| 63 | + } |
| 64 | + |
| 65 | + variants += countTowelVariants(remaining.substring(towel.length)); |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + canBeCompleted.set(remaining, variants); |
| 70 | + return variants; |
| 71 | + }; |
| 72 | + |
| 73 | + for (const design of designs) { |
| 74 | + possibleDesigns += countTowelVariants(design); |
| 75 | + } |
| 76 | + |
| 77 | + return possibleDesigns; |
| 78 | +}); |
0 commit comments