Skip to content

Commit

Permalink
feat(js): add solutions for 2024 day 19
Browse files Browse the repository at this point in the history
  • Loading branch information
timkurvers committed Dec 21, 2024
1 parent 531a486 commit 6f895c3
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
48 changes: 48 additions & 0 deletions js/src/2024/19/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { solution } from '../../utils/index.js';

const parse = (input) => {
const parts = input.trim().split('\n\n');

const available = parts[0].split(', ');
const desired = parts[1].split('\n');

return { available, desired };
};

// Calculates whether a given design is possible and returns how many variations
const build = (design, available, cache = new Map()) => {
if (cache.has(design)) {
return cache.get(design);
}

let count = 0;
for (const pattern of available) {
if (design.startsWith(pattern)) {
const remaining = design.slice(pattern.length);

if (!remaining.length) {
count += 1;
continue;
}

count += build(remaining, available, cache);
}
}
cache.set(design, count);
return count;
};

export const partOne = solution((input) => {
const { available, desired } = parse(input);
return desired.reduce((sum, design) => {
if (build(design, available)) {
return sum + 1;
}
return sum;
}, 0);
});

export const partTwo = solution((input) => {
const { available, desired } = parse(input);
return desired.reduce((sum, design) => sum + build(design, available), 0);
});
17 changes: 17 additions & 0 deletions puzzles/2024/19/examples.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
part-one:
- input: &example1 |
r, wr, b, g, bwu, rb, gb, br

brwrr
bggr
gbbr
rrbgbr
ubwu
bwurrg
brgr
bbrgwb
answer: 6

part-two:
- input: *example1
answer: 16

0 comments on commit 6f895c3

Please sign in to comment.