Skip to content

Commit b32d57d

Browse files
committed
Solution for day 12 (2019)
1 parent 3b72142 commit b32d57d

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

2019/12/index.js

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
const fs = require('fs')
2+
3+
const coords = [0, 1, 2]
4+
const gcd = (a, b) => a ? gcd(b % a, a) : b
5+
const lcm = (a, b) => a * b / gcd(a, b)
6+
7+
fs.readFile(`${__dirname}/input.txt`, (_e, data) => {
8+
const moons = data.toString().split('\n').filter(v => v.length).map(makeMoon)
9+
console.log('Part 1', part1(moons))
10+
console.log('Part 2', part2(moons))
11+
})
12+
13+
function part1(init) {
14+
const moons = JSON.parse(JSON.stringify(init))
15+
for (let i = 0; i < 1000; i++) {
16+
coords.forEach(c => update(moons, c))
17+
}
18+
return systemEnergy(moons)
19+
}
20+
21+
function part2(init) {
22+
const moons = JSON.parse(JSON.stringify(init))
23+
let results = [];
24+
coords.forEach(c => {
25+
for (let i = 0; true; i++) {
26+
update(moons, c)
27+
if (!moons.find((m, i) => m.pos[c] !== init[i].pos[c] || m.vel[c] !== 0)) {
28+
return results[c] = i + 1
29+
}
30+
}
31+
})
32+
return results.reduce(lcm, 1)
33+
}
34+
35+
function update(moons, c) {
36+
moons.forEach(a => moons.forEach(b => {
37+
if (a.pos[c] > b.pos[c]) a.vel[c]--
38+
else if (a.pos[c] < b.pos[c]) a.vel[c]++
39+
}))
40+
moons.forEach(moon => moon.pos[c] += moon.vel[c])
41+
}
42+
43+
function systemEnergy(moons) {
44+
return moons.map(moonEnergy).reduce((a, b) => a + b, 0)
45+
}
46+
47+
function moonEnergy(moon) {
48+
const potential = moon.pos.reduce((a, b) => Math.abs(a) + Math.abs(b), 0)
49+
const kinetic = moon.vel.reduce((a, b) => Math.abs(a) + Math.abs(b), 0)
50+
return potential * kinetic
51+
}
52+
53+
function makeMoon(str, i) {
54+
return {
55+
name: ['Io', 'Europa', 'Ganymede', 'Callisto'][i],
56+
pos: [
57+
parseInt(/x\=([-\d]*)/g.exec(str)[1]),
58+
parseInt(/y\=([-\d]*)/g.exec(str)[1]),
59+
parseInt(/z\=([-\d]*)/g.exec(str)[1])
60+
],
61+
vel: [0, 0, 0]
62+
}
63+
}

2019/12/input.txt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<x=3, y=2, z=-6>
2+
<x=-13, y=18, z=10>
3+
<x=-8, y=-1, z=13>
4+
<x=5, y=10, z=4>

0 commit comments

Comments
 (0)