Created
December 13, 2021 22:48
-
-
Save ablamunits/c92ad07348015868f35dd0abe33b27af to your computer and use it in GitHub Desktop.
AoC 2021 Day 13
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type FoldInstruction = { | |
axis: 'x' | 'y'; | |
value: number; | |
} | |
type Input = { | |
points: Map<string, Point>; | |
foldInstructions: FoldInstruction[]; | |
} | |
type Point = [number, number]; | |
const parseInput = (input: string): Input => { | |
const [rawPoints, rawInstructions] = input.trim().split(/\n\n/g); | |
const points: Map<string, Point> = new Map(); | |
rawPoints.split(/\n/).forEach((rp) => { | |
const [x, y] = rp.split(',').map(Number); | |
points.set(`${x},${y}`, [x, y]); | |
}) | |
const foldInstructions: FoldInstruction[] = rawInstructions.split(/\n/g).map(t => t.replace(/fold along /g, '')).map((ri) => { | |
const [axis, v] = ri.split('='); | |
return { | |
axis: axis as 'x' | 'y', | |
value: Number(v), | |
} | |
}); | |
return { | |
points, | |
foldInstructions, | |
} | |
} | |
const performFold = (points: Map<string, Point>, fold: FoldInstruction): Map<string, Point> => { | |
Array.from(points.values()).forEach((point) => { | |
const [x, y] = point; | |
const coordVal = fold.axis === 'x' ? x : y; | |
if (coordVal >= fold.value) { | |
points.delete(`${x},${y}`); | |
const newCoord = 2 * fold.value - coordVal; | |
const pt = fold.axis === 'x' ? [newCoord, y] : [x, newCoord]; | |
points.set(pt.join(','), pt as Point); | |
} | |
}) | |
return points; | |
} | |
export const solveP1 = (input: string) => { | |
const { points, foldInstructions } = parseInput(input); | |
performFold(points, foldInstructions[0]); | |
return points.size; | |
}; | |
export const solveP2 = (input: string) => { | |
const { points, foldInstructions } = parseInput(input); | |
foldInstructions.forEach(inst => performFold(points, inst)); | |
render(points) | |
} | |
const render = (points: Map<string, Point>) => { | |
const pts = Array.from(points.values()); | |
const width = Math.max(...pts.map(p => p[0])) + 1; | |
const height = Math.max(...pts.map(p => p[1])) + 1; | |
const row: string[] = Array(width).fill('.'); | |
const map: string[][] = Array(height).fill(null).map(() => [...row]); | |
points.forEach(([x, y]) => map[y][x] = '#'); | |
map.forEach(row => console.log(row.join('.'))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment