Skip to content

Commit d918a7d

Browse files
committed
feat: Day 12: Subterranean Sustainability (part 2)
1 parent e5ad64f commit d918a7d

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

day-12-subterranean-sustainability/README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,5 +71,11 @@ In this example, after 20 generations, the pots shown as `#` contain plants, the
7171

7272
**After `20` generations, what is the sum of the numbers of all pots which contain a plant?**
7373

74+
## Part Two
75+
76+
You realize that 20 generations aren't enough. After all, these plants will need to last another 1500 years to even reach your timeline, not to mention your future.
77+
78+
**After fifty billion (`50000000000`) generations, what is the sum of the numbers of all pots which contain a plant?**
79+
7480
## References
7581
- https://adventofcode.com/2018/day/12
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
const sustainability = (input) => {
2+
const lines = input.split('\n');
3+
const initialState = lines[0]
4+
.replace('initial state:', '')
5+
.trim()
6+
.split('');
7+
8+
const notes = lines
9+
.slice(2, lines.length)
10+
.map((line) => {
11+
const parts = line.trim().split(' => ');
12+
13+
return {
14+
pattern: parts[0],
15+
outcome: parts[1],
16+
};
17+
});
18+
19+
const mutations = [];
20+
21+
let offset = 10;
22+
let state = [
23+
...'.'.repeat(offset).split(''),
24+
...initialState,
25+
...'.'.repeat(offset).split(''),
26+
];
27+
28+
let generation = 1;
29+
30+
// eslint-disable-next-line no-constant-condition
31+
while (true) {
32+
let nextState = [...'.'.repeat(state.length).split('')];
33+
34+
for (let i = 0; i < state.length; i++) {
35+
const pot = state.slice(i, i + 5).join('');
36+
const note = notes.find(({ pattern }) => pattern === pot);
37+
38+
if (note) {
39+
nextState[i + 2] = note.outcome;
40+
}
41+
}
42+
43+
const i = [...nextState].reverse().indexOf('#');
44+
const padding = i < 5 ? 5 - i : 0;
45+
46+
nextState = [...nextState, ...'.'.repeat(padding).split('')];
47+
48+
state = nextState;
49+
50+
const mutation = state
51+
.join('')
52+
.replace(/\./g, ' ')
53+
.trim();
54+
55+
if (mutations.includes(mutation)) {
56+
break;
57+
} else {
58+
mutations.push(mutation);
59+
}
60+
61+
generation++;
62+
}
63+
64+
return state
65+
.map((x, i) => x === '#' ? i - offset + 50000000000 - generation : 0)
66+
.reduce((a, b) => a + b, 0);
67+
};
68+
69+
module.exports = sustainability;

0 commit comments

Comments
 (0)