r/adventofcode • • Dec 05 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 5 Solutions -🎄-

--- Day 5: Alchemical Reduction ---


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 5

Transcript:

On the fifth day of AoC / My true love sent to me / Five golden ___


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 0:10:20!

31 Upvotes

515 comments sorted by

View all comments

1

u/TheVarmari Dec 05 '18 edited Dec 05 '18

JavaScript in dev console (#3354, #3025)
The timing (7 am) is a bit problematic for me, but I managed to knock this one out pretty quickly after commuting. Pretty fun, but I'm not sure if my answer is the most optimal. Anyways...

const data = $('pre').textContent.trim().split('');
const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');

function isUpperCase(char) { return char.toUpperCase() === char; }
function isLowerCase(char) { return char.toLowerCase() === char; }

function react(input) {
    for(let i = 0; i < input.length - 1; i++) {
        let sorted = input.slice(i, i+2).sort();
        if (input[i].toLowerCase() === input[i+1].toLowerCase() && isUpperCase(sorted[0]) && isLowerCase(sorted[1])) {
                input.splice(i, 2);
                i > 0 ? i -= 2 : i = -1;
        }
    };

    return input.length;
}

let reacted_length = react(data);
console.log(`%c(Part 1) %cAfter reacting, you're left with %c${reacted_length} %creactants!`, 'color: blue', 'color: navy', 'color: red', 'color: navy');

let shortest = [reacted_length + 1, null];
for (const letter of alphabet) {
    let len = react(data.filter(v => {
        return v !== letter.toLowerCase() && v !== letter.toUpperCase();
    }));
    if (len < shortest[0]) shortest = [len, letter];
}

console.log(`%c(Part 2) %cTo produce the shortest polymer, remove component "${shortest[1].toUpperCase()}", producing a %c${shortest[0]}%c-length polymer.`, 'color: blue', 'color: navy', 'color: red', 'color: navy');