2024-12-07 01:23:52 +01:00
|
|
|
|
|
|
|
import { solvables } from "../main.ts";
|
|
|
|
|
|
|
|
import type { Solvable } from "../solvable.ts";
|
|
|
|
import { readInput } from "../utils.ts";
|
|
|
|
|
|
|
|
class DayFive implements Solvable {
|
2024-12-07 02:16:43 +01:00
|
|
|
input: string[] = readInput('05').split('\n\n')
|
2024-12-07 01:23:52 +01:00
|
|
|
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)))
|
|
|
|
|
2024-12-07 02:16:43 +01:00
|
|
|
// generated in part 1 for part 2
|
2024-12-07 01:23:52 +01:00
|
|
|
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)
|
|
|
|
|
2024-12-08 00:46:45 +01:00
|
|
|
public part1(): Promise<Solvable> {
|
2024-12-07 01:23:52 +01:00
|
|
|
const validUpdates: number[][] = []
|
|
|
|
this.updates.forEach(update => {
|
|
|
|
if (this.followsRules(update)[0]) {
|
|
|
|
validUpdates.push(update)
|
|
|
|
} else {
|
2024-12-07 02:16:43 +01:00
|
|
|
// store these for part 2
|
2024-12-07 01:23:52 +01:00
|
|
|
this.invalidUpdates.push(update)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
const result = this.middles(validUpdates)
|
|
|
|
console.log(result)
|
|
|
|
|
2024-12-08 00:46:45 +01:00
|
|
|
return new Promise(() => this)
|
2024-12-07 01:23:52 +01:00
|
|
|
}
|
|
|
|
|
2024-12-08 00:46:45 +01:00
|
|
|
public part2(): Promise<Solvable> {
|
2024-12-07 01:23:52 +01:00
|
|
|
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
|
2024-12-07 01:29:29 +01:00
|
|
|
const removedLeft = update.splice(leftIdx, 1)[0]
|
|
|
|
const rebuiltUpdate = [...update.slice(0, rightIdx), removedLeft, ...update.slice(rightIdx)]
|
2024-12-07 01:23:52 +01:00
|
|
|
return sort(rebuiltUpdate)
|
|
|
|
} else {
|
|
|
|
return update
|
|
|
|
}
|
|
|
|
}
|
|
|
|
const fixedUpdates = invalidUpdates.map(updates => sort(updates))
|
|
|
|
const result = this.middles(fixedUpdates)
|
|
|
|
console.log(result)
|
2024-12-08 00:46:45 +01:00
|
|
|
return new Promise(() => this)
|
2024-12-07 01:23:52 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
solvables.push(new DayFive())
|