r/adventofcode • • Dec 12 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 12 Solutions -🎄-

--- Day 12: Subterranean Sustainability ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 12

Transcript:

On the twelfth day of AoC / My compiler spewed at me / Twelve ___


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked at 00:27:42!

20 Upvotes

257 comments sorted by

View all comments

Show parent comment

1

u/aoc-fan Dec 12 '18

Here is my TS solution

const parse = (ip: string) => {
    const lines = getInput(ip).split("\n");
    const initialState = lines[0].split(": ")[1];
    lines.shift();
    lines.shift();
    const combinations = lines.map(l => l.split(" => ")).reduce((acc, [c, r]) => {
        acc[c] = r;
        return acc;
    }, {} as Dictionary<string>);
    return { initialState, combinations};
};

const growPlants = (ip: string, generationsToWatch: number) => {
    const { initialState, combinations } = parse(ip);
    let [pots, grownPots] = [initialState, ""];
    let [generation, sum, lastSum, lastDiff, streak] = [0, 0, 0, 0, 0];
    while (generation < generationsToWatch) {
        generation = generation + 1;
        pots = "...." + pots + "....";
        grownPots = "";
        sum = 0;
        for (let i = 2; i <= pots.length - 3; i++) {
            const pot = combinations[pots.substr(i - 2, 5)];
            if (pot === "#") {
                sum = sum + i + ((generation * -2) - 2);
            }
            grownPots = grownPots + pot;
        }
        pots = grownPots;
        if (sum - lastSum === lastDiff) {
            streak = streak + 1;
            if (streak === 3) {
                return (generationsToWatch - generation) * lastDiff + sum;
            }
        } else {
            lastDiff = sum - lastSum;
            streak = 0;
        }
        lastSum = sum;
    }
    return sum;
};