answers for day 9

This commit is contained in:
Eric Wagoner 2022-12-09 18:25:38 -05:00
parent 7268243458
commit b69c454c4c
3 changed files with 2140 additions and 0 deletions

132
09/code.js Normal file
View File

@ -0,0 +1,132 @@
const fs = require('fs');
//const inputArray = fs.readFileSync('sample.txt').toString().split("\n");
const inputArray = fs.readFileSync('input.txt').toString().split("\n");
// Part One
const head = [[0, 0]];
const tail = [[0, 0]];
for (i in inputArray) {
const contents = inputArray[i].split(" ");
const dir = contents[0];
const dist = contents[1];
for (m = 1; m <= dist; m++) {
let hx = head[0][0];
let hy = head[0][1];
let tx = tail[0][0];
let ty = tail[0][1];
if (dir === 'U') {
hy++;
} else if (dir === "D") {
hy--;
} else if (dir === "L") {
hx--;
} else if (dir === "R") {
hx++;
}
head.unshift([hx, hy]);
tail.unshift(walk(hx, hy, tx, ty));
}
}
let strings = [];
for (pos of tail) {
strings.push(pos.join('-'));
}
let touched = [...new Set(strings)];
console.log(touched.length);
// Part Two
const h = [[0, 0]];
const one = [[0, 0]];
const two = [[0, 0]];
const three = [[0, 0]];
const four = [[0, 0]];
const five = [[0, 0]];
const six = [[0, 0]];
const seven = [[0, 0]];
const eight = [[0, 0]];
const t = [[0, 0]];
for (i in inputArray) {
const contents = inputArray[i].split(" ");
const dir = contents[0];
const dist = contents[1];
for (m = 1; m <= dist; m++) {
let hx = h[0][0];
let hy = h[0][1];
if (dir === 'U') {
hy++;
} else if (dir === "D") {
hy--;
} else if (dir === "L") {
hx--;
} else if (dir === "R") {
hx++;
}
h.unshift([hx, hy]);
one.unshift(walk(hx, hy, one[0][0], one[0][1]));
two.unshift(walk(one[0][0], one[0][1], two[0][0], two[0][1]));
three.unshift(walk(two[0][0], two[0][1], three[0][0], three[0][1]));
four.unshift(walk(three[0][0], three[0][1], four[0][0], four[0][1]));
five.unshift(walk(four[0][0], four[0][1], five[0][0], five[0][1]));
six.unshift(walk(five[0][0], five[0][1], six[0][0], six[0][1]));
seven.unshift(walk(six[0][0], six[0][1], seven[0][0], seven[0][1]));
eight.unshift(walk(seven[0][0], seven[0][1], eight[0][0], eight[0][1]));
t.unshift(walk(eight[0][0], eight[0][1], t[0][0], t[0][1]));
}
}
strings = [];
for (pos of t) {
strings.push(pos.join('-'));
}
touched = [...new Set(strings)];
console.log(touched.length);
// functions
function walk(hx, hy, tx, ty) {
if ((hx > tx) && Math.abs(hx - tx) >= 2) {
tx++;
if (hy > ty) {
ty++;
} else if (ty > hy) {
ty--;
}
} else if ((tx > hx) && Math.abs(tx - hx) >= 2) {
tx--;
if (hy > ty) {
ty++;
} else if (ty > hy) {
ty--;
}
} else if ((hy > ty) && Math.abs(hy - ty) >= 2) {
ty++;
if (hx > tx) {
tx++;
} else if (tx > hx) {
tx--;
}
} else if ((ty > hy) && Math.abs(ty - hy) >= 2) {
ty--;
if (hx > tx) {
tx++;
} else if (tx > hx) {
tx--;
}
}
return [tx, ty]
}

2000
09/input.txt Normal file

File diff suppressed because it is too large Load Diff

8
09/sample.txt Normal file
View File

@ -0,0 +1,8 @@
R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20