82 lines
2.3 KiB
TypeScript
82 lines
2.3 KiB
TypeScript
import { readFileSync } from 'fs';
|
|
import { join } from 'path';
|
|
|
|
function distance(p1: number[], p2: number[]): number {
|
|
var x = p1[0] - p2[0];
|
|
var y = p1[1] - p2[1];
|
|
return Math.abs(x) + Math.abs(y)
|
|
}
|
|
|
|
const clamp = (num, min, max) => Math.min(Math.max(num, min), max);
|
|
|
|
const fileString = readFileSync(join(__dirname, "inp"), 'utf-8');
|
|
var commands = fileString.split("\n");
|
|
commands = commands.filter(val => {
|
|
return val.length > 0;
|
|
})
|
|
commands = commands.map(val => {
|
|
return val.trim();
|
|
})
|
|
const cmds = commands.map(val => {
|
|
return val.split(" ");
|
|
})
|
|
|
|
console.log(cmds);
|
|
|
|
var positions = {};
|
|
|
|
var pointlist = [];
|
|
const POINTS = 10;
|
|
for (var l = 0; l < POINTS; l++) {
|
|
pointlist.push([0, 0])
|
|
}
|
|
positions[pointlist[0].toString()] = 1;
|
|
|
|
for (const command of cmds) {
|
|
const direction = command[0];
|
|
const count = +command[1];
|
|
for (var j = 0; j < POINTS; j++){
|
|
for (var k = 0; k < count; k ++) {
|
|
if (j == 0) {
|
|
switch(direction) {
|
|
case 'U':
|
|
pointlist[j] = [pointlist[j][0], pointlist[j][1] + 1];
|
|
break;
|
|
case 'D':
|
|
pointlist[j] = [pointlist[j][0], pointlist[j][1] - 1];
|
|
break;
|
|
case 'L':
|
|
pointlist[j] = [pointlist[j][0] - 1, pointlist[j][1]];
|
|
break;
|
|
case 'R':
|
|
pointlist[j] = [pointlist[j][0] + 1, pointlist[j][1]];
|
|
break;
|
|
}
|
|
} else {
|
|
var currentPosition = pointlist[j];
|
|
var currentHeadPosition = pointlist[j - 1];
|
|
if (
|
|
(Math.abs(currentHeadPosition[0] - currentPosition[0]) > 1) ||
|
|
(Math.abs(currentHeadPosition[1] - currentPosition[1]) > 1)
|
|
) {
|
|
var xdiff = clamp(currentHeadPosition[0] - currentPosition[0], -1, 1);
|
|
var ydiff = clamp(currentHeadPosition[1] - currentPosition[1], -1, 1);
|
|
currentPosition = [currentPosition[0] + xdiff, currentPosition[1] + ydiff];
|
|
pointlist[j] = currentPosition;
|
|
|
|
if (j == 9) {
|
|
if(currentPosition.toString() in positions) {
|
|
positions[currentPosition.toString()] += 1;
|
|
} else {
|
|
positions[currentPosition.toString()] = 1;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
console.log(pointlist);
|
|
}
|
|
|
|
console.log(Object.keys(positions).length);
|