79 lines
2.3 KiB
TypeScript
79 lines
2.3 KiB
TypeScript
|
import { transformEdgeLine, Direction, Instruction, readInput, calcArea } from "./solver.ts";
|
||
|
|
||
|
async function NewReadInput(filename: string): Promise<Instruction[]> {
|
||
|
const input = await Deno.readTextFile(filename);
|
||
|
const lines = input.split("\n").map(x => x.trim()).filter(x => x.length > 0);
|
||
|
return lines.map(line => {
|
||
|
const m = /^([RDLU])\s+(\d+)\s+\(#([0-9a-f]+)\)$/.exec(line);
|
||
|
if (!m) {
|
||
|
throw new Error(`unknown line ${line}`);
|
||
|
}
|
||
|
const steps = parseInt(m[3].slice(0,5), 16);
|
||
|
const direction = {
|
||
|
[0]: "R",
|
||
|
[1]: "D",
|
||
|
[2]: "L",
|
||
|
[3]: "U",
|
||
|
}[parseInt(m[3].slice(5,6))];
|
||
|
return {
|
||
|
direction: direction as Direction,
|
||
|
steps,
|
||
|
color: parseInt(m[3], 16),
|
||
|
}
|
||
|
});
|
||
|
}
|
||
|
|
||
|
const input = await NewReadInput("example.txt");
|
||
|
// console.log(input)
|
||
|
|
||
|
function calcWidthAndHeight(insts: Instruction[]){
|
||
|
let maxX = 0, maxY = 0;
|
||
|
let minX = 0, minY = 0;
|
||
|
insts.reduce<[number,number]>(([x,y]: [number, number], b: Instruction) => {
|
||
|
maxX = Math.max(maxX, x);
|
||
|
maxY = Math.max(maxY, y);
|
||
|
minX = Math.min(minX, x);
|
||
|
minY = Math.min(minY, y);
|
||
|
|
||
|
if (b.direction === "R"){
|
||
|
return [x + b.steps, y];
|
||
|
}
|
||
|
if (b.direction === "L"){
|
||
|
return [x - b.steps, y];
|
||
|
}
|
||
|
if (b.direction === "U"){
|
||
|
return [x, y - b.steps];
|
||
|
}
|
||
|
if (b.direction === "D"){
|
||
|
return [x, y + b.steps];
|
||
|
}
|
||
|
throw new Error(`unknown direction ${b.direction}`);
|
||
|
}, [0,0] as [number, number]);
|
||
|
return {
|
||
|
size: [maxX - minX + 1, maxY - minY + 1],
|
||
|
initPos: [-minX, -minY]
|
||
|
};
|
||
|
}
|
||
|
const {size:[width, height],
|
||
|
initPos: [initX, initY]} = calcWidthAndHeight(input);
|
||
|
|
||
|
console.log((`x: ${width}, y: ${height}`));
|
||
|
|
||
|
let pos = [initX, initY];
|
||
|
transformEdgeLine(input).forEach(inst => {
|
||
|
if (inst.direction === "R"){
|
||
|
pos = [pos[0] + inst.steps, pos[1]];
|
||
|
}
|
||
|
if (inst.direction === "L"){
|
||
|
pos = [pos[0] - inst.steps, pos[1]];
|
||
|
}
|
||
|
if (inst.direction === "U"){
|
||
|
pos = [pos[0], pos[1] - inst.steps];
|
||
|
}
|
||
|
if (inst.direction === "D"){
|
||
|
pos = [pos[0], pos[1] + inst.steps];
|
||
|
}
|
||
|
// console.log(`(${pos[0]}, ${pos[1]})`, inst);
|
||
|
});
|
||
|
|
||
|
console.log(calcArea(input));
|