Skip to content

Commit

Permalink
feat(js): add solutions for 2023 day 3
Browse files Browse the repository at this point in the history
  • Loading branch information
timkurvers committed Dec 3, 2023
1 parent 48b9bd9 commit 4ff47b7
Show file tree
Hide file tree
Showing 4 changed files with 218 additions and 1 deletion.
3 changes: 2 additions & 1 deletion js/.eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
"no-unused-vars": ["warn", {
"argsIgnorePattern": "^_",
"varsIgnorePattern": "^_"
}]
}],
"object-curly-newline": "off"
},
"overrides": [
{
Expand Down
59 changes: 59 additions & 0 deletions js/src/2023/03/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { Grid, cast, isNumber, multiply, solution, sum } from '../../utils';

const EMPTY = '.';
const GEAR = '*';

const parse = (input) => Grid.from(input, { cast });

const isGear = (point) => point.value === GEAR;
const isSymbol = (point) => !isNumber(point.value) && point.value !== EMPTY;

const process = (schema) => {
const parts = [];
let current = { part: 0, gears: new Set(), valid: false };
for (const point of schema.points) {
const { neighbors, value } = point;

if (!isNumber(value)) continue;

current.part = current.part * 10 + value;

for (const neighbor of neighbors) {
if (isSymbol(neighbor)) {
current.valid = true;
}
if (isGear(neighbor)) {
current.gears.add(neighbor);
}
}

if (!point.right || !isNumber(point.right.value)) {
if (current.valid) {
// Have reached the end of a valid part number
parts.push(current.part);
for (const gear of current.gears) {
(gear.parts ||= []).push(current.part);
}
}
current = { part: 0, gears: new Set(), valid: false };
}
}

const gears = schema.filter((point) => (
isGear(point) && point.parts.length === 2
));

return { parts, gears };
};

export const partOne = solution((input) => {
const schema = parse(input);
const { parts } = process(schema);
return sum(parts);
});

export const partTwo = solution((input) => {
const schema = parse(input);
const { gears } = process(schema);
return sum(gears.map((gear) => multiply(gear.parts)));
});
17 changes: 17 additions & 0 deletions puzzles/2023/03/examples.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
part-one:
- input: &example1 |
467..114..
...*......
..35..633.
......#...
617*......
.....+.58.
..592.....
......755.
...$.*....
.664.598..
answer: 4361

part-two:
- input: *example1
answer: 467835
Loading

0 comments on commit 4ff47b7

Please sign in to comment.