Created
December 15, 2018 05:28
-
-
Save jemmyw/e94622ed91fcc6f2c2650358bae58e38 to your computer and use it in GitHub Desktop.
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
import * as fs from 'fs'; | |
type Point = [number, number] | |
interface PointInput { | |
p: Point | |
v: Point | |
} | |
const pointInput = fs.readFileSync('10.txt').toString() | |
.split("\n") | |
.filter(s => s.trim() !== '') | |
.map(line => { | |
const posMatch = line.match(/position=<\s*(-?\d+),\s*(-?\d+)>/); | |
const velMatch = line.match(/velocity=<\s*(-?\d+),\s*(-?\d+)>/); | |
return { p: [posMatch[1], posMatch[2]].map(Number), v: [velMatch[1], velMatch[2]].map(Number) } as PointInput; | |
}) | |
function pointAfter(p: PointInput, s: number) { | |
const x = p.p[0]; | |
const y = p.p[1]; | |
const xv = p.v[0]; | |
const yv = p.v[1]; | |
return [ | |
x + (xv * s), | |
y + (yv * s) | |
] as Point; | |
} | |
function pointsAfter(p: PointInput[], s: number) { | |
return p.map(p => pointAfter(p, s)); | |
} | |
function pointStr(p: Point) { | |
return p.join(','); | |
} | |
function gridSize(points: Point[]): [Point, Point] { | |
const xs = points.map(p => p[0]); | |
const ys = points.map(p => p[1]); | |
return [ | |
[Math.min(...xs), Math.min(...ys)], | |
[Math.max(...xs), Math.max(...ys)] | |
] | |
} | |
function draw(points: Point[]) { | |
const [[minX, minY], [maxX, maxY]] = gridSize(points); | |
const pointMap = points.reduce((acc, p) => { | |
acc[pointStr(p)] = true | |
return acc; | |
}, {}) | |
for (let y = minY; y <= maxY; ++y) { | |
for (let x = minX; x <= maxX; ++x) { | |
const l = pointMap[pointStr([x, y])] ? '#' : '.'; | |
process.stdout.write(l); | |
} | |
process.stdout.write("\n"); | |
} | |
} | |
function sizeGrid(size: [Point, Point]) { | |
return (size[1][0] - size[0][0]) + (size[1][1] - size[0][1]); | |
} | |
function getMinSize(pointInput) { | |
let s = 0 | |
while(true) { | |
const gs = sizeGrid(gridSize(pointsAfter(pointInput, s))); | |
const gsn = sizeGrid(gridSize(pointsAfter(pointInput, s + 1))); | |
if (gs <= gsn) return s; | |
s++; | |
} | |
} | |
const minSizeAt = getMinSize(pointInput); | |
console.log(minSizeAt); | |
draw(pointsAfter(pointInput, minSizeAt)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment