TypeScript Day 10

https://github.com/romellem/advent-of-code/blob/master/2019/10/
This commit is contained in:
Tobias Berger 2020-11-20 09:56:04 +01:00
parent 43b14b582a
commit c33fa5b120
Signed by: toby
GPG key ID: 2D05EFAB764D6A88
9 changed files with 147814 additions and 0 deletions

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,5 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
yarn-path ".yarn/releases/yarn-1.22.10.cjs"

View file

@ -0,0 +1,205 @@
// @link https://en.wikipedia.org/wiki/Euclidean_algorithm#Implementations
function gcd(a: number, b: number): number {
if (b === 0) return a;
return gcd(b, a % b);
}
/**
* Given an x,y point, returns an angle 0-360
* such that the top of the circle is 0, and then
* we rotate clockwise.
*
* So in the below ascii circle, if you start at
* point `0`, then you'll visit the points 1, 2, 3,
* etc., in order.
*
* 9 0 1
* 8 2
* 7 3
* 6 5 4
*
* In addition, my plane has negative y's going up
* and positive y's going down.
*
* -y ^
* |
* -x <---+---> +x
* |
* +y v
*/
function coordToAngle([x, y]: [number, number]) {
let deg = (Math.atan2(-y, x) * 180) / Math.PI;
// Pretty sure this can be simplified with a modulus, but can't see it
if (deg <= 90 && deg >= 0) {
deg = Math.abs(deg - 90);
} else if (deg < 0) {
deg = Math.abs(deg) + 90;
} else {
deg = 450 - deg;
}
return deg;
}
export class Grid {
min_x: number;
min_y: number;
max_x: number;
max_y: number;
grid: number[][]; // @TODO
asteroids: [number, number][];
constructor(input: (1|0)[][]) {
// `1` is an asteroid, `0` is open space
this.grid = JSON.parse(JSON.stringify(input));
this.asteroids = this.getAsteroidsList();
this.min_x = 0;
this.min_y = 0;
this.max_x = this.grid[0].length - 1;
this.max_y = this.grid.length - 1;
}
getAsteroidsList() {
let asteroids: [number, number][] = [];
for (let y = 0; y < this.grid.length; y++) {
for (let x = 0; x < this.grid[y].length; x++) {
if (this.grid[y][x]) {
asteroids.push([x, y]);
}
}
}
return asteroids;
}
getVectorsFromPoint(coord: [number, number], sorted_clockwise = false) {
let slopes: Record<string, boolean> = {};
const [x1, y1] = coord;
// This isn't optimized (its O(n^2)) but it works for grids of this size.
for (let y2 = 0; y2 <= this.max_y; y2++) {
for (let x2 = 0; x2 <= this.max_x; x2++) {
if (x1 === x2 && y1 === y2) {
continue;
}
let dy = y2 - y1;
let dx = x2 - x1;
let divisor = Math.abs(gcd(dy, dx));
dy /= divisor;
dx /= divisor;
// Technically I'm storing inverse slopes of `x/y` but that is so my `map` function below spits out `[x, y]` coords
slopes[`${dx}/${dy}`] = true;
}
}
const vectors_to_travel = Object.keys(slopes).map((slope_str) =>
slope_str.split("/").map((v) => parseInt(v, 10))
) as [number, number][];
if (sorted_clockwise) {
vectors_to_travel.sort((p1, p2) => {
let p1_d = coordToAngle(p1);
let p2_d = coordToAngle(p2);
return p1_d - p2_d;
});
}
return vectors_to_travel;
}
// Part one
getAsteroidWithHighestCountInLineOfSight() {
let best_count = -1;
let best_coords = null;
for (let asteroid of this.asteroids) {
let vectors = this.getVectorsFromPoint(asteroid);
let count = vectors
.map((vector) => (this.getCollisionAlongVector(asteroid, vector) ? 1 : 0))
.reduce((a: number, b) => a + b, 0);
if (count > best_count) {
best_count = count;
best_coords = asteroid;
}
}
return {
best_count,
best_coords,
};
}
// Part two
vaporizeAsteroidsFrom(start_from: [number, number] | null): number {
if (!start_from) {
({ best_coords: start_from } = this.getAsteroidWithHighestCountInLineOfSight());
const throw_error = (): [number, number] => {
throw new Error("start_from is null");
};
start_from = start_from ?? throw_error();
}
let total_vaporized = 0;
let vaporized = [];
do {
let clockwise_vectors_from_start = this.getVectorsFromPoint(start_from, true);
for (let vector of clockwise_vectors_from_start) {
let collision_coord = this.getCollisionAlongVector(start_from, vector);
if (collision_coord) {
total_vaporized++;
this.vaporize(collision_coord);
vaporized.push(collision_coord);
}
if (total_vaporized === 200) {
let [x, y] = collision_coord ?? [0, 0];
return x * 100 + y;
}
}
// } while (this.sumAllAsteroids() > 1);
} while (total_vaporized < 200);
return -Infinity;
}
getCollisionAlongVector(from: [number, number], vector: [number, number]) {
let collision_coord: [number, number] | null = null;
const [x, y] = from;
const [vx, vy] = vector;
let new_x = x + vx;
let new_y = y + vy;
while (this.pointInGrid(new_x, new_y)) {
if (this.grid[new_y][new_x]) {
collision_coord = [new_x, new_y];
break;
}
new_x += vx;
new_y += vy;
}
return collision_coord;
}
vaporize([x, y]: [number, number]) {
this.grid[y][x] = 0;
}
pointInGrid(x: number, y: number) {
return x >= this.min_x && x <= this.max_x && y >= this.min_y && y <= this.max_y;
}
sumAllAsteroids() {
let sum = 0;
for (let y = 0; y < this.grid.length; y++) {
for (let x = 0; x < this.grid[y].length; x++) {
sum += this.grid[y][x];
}
}
return sum;
}
}

View file

@ -0,0 +1,36 @@
....#...####.#.#...........#........
#####..#.#.#......#####...#.#...#...
##.##..#.#.#.....#.....##.#.#..#....
...#..#...#.##........#..#.......#.#
#...##...###...###..#...#.....#.....
##.......#.....#.........#.#....#.#.
..#...#.##.##.....#....##..#......#.
..###..##..#..#...#......##...#....#
##..##.....#...#.#...#......#.#.#..#
...###....#..#.#......#...#.......#.
#....#...##.......#..#.......#..#...
#...........#.....#.....#.#...#.##.#
###..#....####..#.###...#....#..#...
##....#.#..#.#......##.......#....#.
..#.#....#.#.#..#...#.##.##..#......
...#.....#......#.#.#.##.....#..###.
..#.#.###.......#..#.#....##.....#..
.#.#.#...#..#.#..##.#..........#...#
.....#.#.#...#..#..#...###.#...#.#..
#..#..#.....#.##..##...##.#.....#...
....##....#.##...#..........#.##....
...#....###.#...##........##.##..##.
#..#....#......#......###...........
##...#..#.##.##..##....#..#..##..#.#
.#....#..##.....#.#............##...
.###.........#....#.##.#..#.#..#.#..
#...#..#...#.#.#.....#....#......###
#...........##.#....#.##......#.#..#
....#...#..#...#.####...#.#..#.##...
......####.....#..#....#....#....#.#
.##.#..###..####...#.......#.#....#.
#.###....#....#..........#.....###.#
...#......#....##...##..#..#...###..
..#...###.###.........#.#..#.#..#...
.#.#.............#.#....#...........
..#...#.###...##....##.#.#.#....#.#.

View file

@ -0,0 +1,16 @@
{
"scripts": {
"lint": "prettier grid.ts solution_a.ts solution_b.ts --write --print-width=120",
"a": "ts-node solution_a.ts",
"b": "ts-node solution_b.ts"
},
"devDependencies": {
"prettier": "^2.1.2"
},
"dependencies": {
"@types/node": "^14.14.8",
"ts-node": "^9.0.0",
"typescript": "^4.0.5"
},
"license": "WTFPL"
}

View file

@ -0,0 +1,12 @@
import {Grid} from './grid'
import * as fs from "fs";
const input = fs.readFileSync("input").toString()
.split('\n')
.map(row => row.split('').map(v => (v === '#' ? 1 : 0)));
async function main() {
const grid = new Grid(input)
return grid.getAsteroidWithHighestCountInLineOfSight()
}
main().then(console.log).catch(console.error);

View file

@ -0,0 +1,12 @@
import {Grid} from './grid'
import * as fs from "fs";
const input = fs.readFileSync("input").toString()
.split('\n')
.map(row => row.split('').map(v => (v === '#' ? 1 : 0)));
async function main() {
const grid = new Grid(input)
return grid.vaporizeAsteroidsFrom(grid.getAsteroidWithHighestCountInLineOfSight().best_coords)
}
main().then(console.log).catch(console.error);

View file

@ -0,0 +1,69 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "ES2019", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "CommonJS", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": false, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
"noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
"alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}

View file

@ -0,0 +1,67 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
"@types/node@^14.14.8":
version "14.14.8"
resolved "https://registry.yarnpkg.com/@types/node/-/node-14.14.8.tgz#2127bd81949a95c8b7d3240f3254352d72563aec"
integrity sha512-z/5Yd59dCKI5kbxauAJgw6dLPzW+TNOItNE00PkpzNwUIEwdj/Lsqwq94H5DdYBX7C13aRA0CY32BK76+neEUA==
arg@^4.1.0:
version "4.1.3"
resolved "https://registry.yarnpkg.com/arg/-/arg-4.1.3.tgz#269fc7ad5b8e42cb63c896d5666017261c144089"
integrity sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==
buffer-from@^1.0.0:
version "1.1.1"
resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.1.tgz#32713bc028f75c02fdb710d7c7bcec1f2c6070ef"
integrity sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==
diff@^4.0.1:
version "4.0.2"
resolved "https://registry.yarnpkg.com/diff/-/diff-4.0.2.tgz#60f3aecb89d5fae520c11aa19efc2bb982aade7d"
integrity sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==
make-error@^1.1.1:
version "1.3.6"
resolved "https://registry.yarnpkg.com/make-error/-/make-error-1.3.6.tgz#2eb2e37ea9b67c4891f684a1394799af484cf7a2"
integrity sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==
prettier@^2.1.2:
version "2.1.2"
resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.1.2.tgz#3050700dae2e4c8b67c4c3f666cdb8af405e1ce5"
integrity sha512-16c7K+x4qVlJg9rEbXl7HEGmQyZlG4R9AgP+oHKRMsMsuk8s+ATStlf1NpDqyBI1HpVyfjLOeMhH2LvuNvV5Vg==
source-map-support@^0.5.17:
version "0.5.19"
resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.19.tgz#a98b62f86dcaf4f67399648c085291ab9e8fed61"
integrity sha512-Wonm7zOCIJzBGQdB+thsPar0kYuCIzYvxZwlBa87yi/Mdjv7Tip2cyVbLj5o0cFPN4EVkuTwb3GDDyUx2DGnGw==
dependencies:
buffer-from "^1.0.0"
source-map "^0.6.0"
source-map@^0.6.0:
version "0.6.1"
resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263"
integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==
ts-node@^9.0.0:
version "9.0.0"
resolved "https://registry.yarnpkg.com/ts-node/-/ts-node-9.0.0.tgz#e7699d2a110cc8c0d3b831715e417688683460b3"
integrity sha512-/TqB4SnererCDR/vb4S/QvSZvzQMJN8daAslg7MeaiHvD8rDZsSfXmNeNumyZZzMned72Xoq/isQljYSt8Ynfg==
dependencies:
arg "^4.1.0"
diff "^4.0.1"
make-error "^1.1.1"
source-map-support "^0.5.17"
yn "3.1.1"
typescript@^4.0.5:
version "4.0.5"
resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.0.5.tgz#ae9dddfd1069f1cb5beb3ef3b2170dd7c1332389"
integrity sha512-ywmr/VrTVCmNTJ6iV2LwIrfG1P+lv6luD8sUJs+2eI9NLGigaN+nUQc13iHqisq7bra9lnmUSYqbJvegraBOPQ==
yn@3.1.1:
version "3.1.1"
resolved "https://registry.yarnpkg.com/yn/-/yn-3.1.1.tgz#1e87401a09d767c1d5eab26a6e4c185182d2eb50"
integrity sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==