day 5 p1 & init p2

This commit is contained in:
mtrx 2024-12-07 01:23:52 +01:00
parent 6c7bc6c648
commit 699d209501
3 changed files with 1433 additions and 2 deletions

View file

@ -32,7 +32,6 @@ class DayFour implements Solvable {
results.push(matrix[y][x] + matrix[y - 1][x + 1] + matrix[y - 2][x + 2] + matrix[y - 3][x + 3])
}
}
if (allowed.bottom) {
// bottom
results.push(matrix[y][x] + matrix[y + 1][x] + matrix[y + 2][x] + matrix[y + 3][x])
@ -45,7 +44,6 @@ class DayFour implements Solvable {
results.push(matrix[y][x] + matrix[y + 1][x + 1] + matrix[y + 2][x + 2] + matrix[y + 3][x + 3])
}
}
if (allowed.left) {
// left
results.push(matrix[y][x] + matrix[y][x - 1] + matrix[y][x - 2] + matrix[y][x - 3])

64
solutions/05.ts Normal file
View file

@ -0,0 +1,64 @@
import { solvables } from "../main.ts";
import type { Solvable } from "../solvable.ts";
import { readInput } from "../utils.ts";
class DayFive implements Solvable {
input: string[] = readInput('05').trim().split('\n\n')
rules: number[][] = this.input[0].split('\n').map((input: string) => input.split('|').map(rule => Number.parseInt(rule)))
updates: number[][] = this.input[1].split('\n').map(line => line.split(',').map(update => Number.parseInt(update)))
invalidUpdates: number[][] = []
followsRules = (update: number[]): [boolean, number, number] => {
for (const rule of this.rules) {
const left = update.findIndex((val) => val === rule[0])
const right = update.findIndex((val) => val === rule[1])
if (left === -1 || right === -1) continue
if (left > right) return [false, left, right]
}
return [true, -1, -1]
}
middles = (updates: number[][]): number =>
updates
.map((update: number[]) => update[Math.floor(update.length / 2)])
.reduce((prev, curr) => prev + curr)
public part1(): Solvable {
const validUpdates: number[][] = []
this.updates.forEach(update => {
if (this.followsRules(update)[0]) {
validUpdates.push(update)
} else {
this.invalidUpdates.push(update)
}
})
const result = this.middles(validUpdates)
console.log(result)
return this
}
public part2(): Solvable {
const invalidUpdates = this.invalidUpdates
const sort = (update: number[]): number[] => {
const [compliant, leftIdx, rightIdx] = this.followsRules(update)
if (!compliant) {
// remove offending item and just move it to the back
const removedLeft = update.splice(leftIdx, 1)
const rebuiltUpdate = [...update.slice(0, rightIdx), removedLeft[0], ...update.slice(rightIdx, -1)]
return sort(rebuiltUpdate)
} else {
return update
}
}
const fixedUpdates = invalidUpdates.map(updates => sort(updates))
const result = this.middles(fixedUpdates)
console.log(result)
return this
}
}
solvables.push(new DayFive())