aoc24/solutions/03.ts

51 lines
1.4 KiB
TypeScript
Raw Normal View History

2024-12-06 02:07:37 +01:00
import { solvables } from "../main.ts";
import type { Solvable } from "../solvable.ts";
import { readInput } from "../utils.ts";
class DayThree implements Solvable {
input = readInput('03')
2024-12-06 02:38:15 +01:00
private multiplyInstruction(inst: string) {
return inst
.slice(4, -1)
.split(',')
.map(arr => Number.parseInt(arr))
}
2024-12-06 02:07:37 +01:00
public part1(): Solvable {
2024-12-06 03:07:23 +01:00
const re = /mul\([0-9]{1,3},[0-9]{1,3}\)/g
2024-12-06 02:07:37 +01:00
const result = this.input.matchAll(new RegExp(re))
2024-12-06 02:38:15 +01:00
.map(match => this.multiplyInstruction(match[0]))
2024-12-06 02:07:37 +01:00
.map(([left, right]) => left * right)
.reduce((prev, curr) => prev + curr)
console.log(result)
return this
}
2024-12-06 02:38:15 +01:00
2024-12-06 02:07:37 +01:00
public part2(): Solvable {
2024-12-06 03:07:23 +01:00
const re = /(mul\([0-9]{1,3},[0-9]{1,3}\)|do\(\)|don\'t\(\))/g
2024-12-06 03:08:30 +01:00
const instructions = this.input.matchAll(new RegExp(re)).map(match => match[0])
2024-12-06 02:38:15 +01:00
let active = true
let result = 0
for (const inst of instructions) {
if (inst === 'do()') {
2024-12-06 03:07:23 +01:00
active = true
2024-12-06 02:38:15 +01:00
continue
}
if (inst === 'don\'t()') {
2024-12-06 03:07:23 +01:00
active = false
continue
2024-12-06 02:38:15 +01:00
}
if (active) {
const [left, right] = this.multiplyInstruction(inst)
result += left * right
}
}
console.log(result)
return this
2024-12-06 02:07:37 +01:00
}
}
solvables.push(new DayThree())