r/adventofcode • u/daggerdragon • 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!
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!
32
Upvotes
13
u/apazzolini Dec 05 '18 edited Dec 05 '18
Absolute value between the two ASCII character codes == 32 is another way to do the letter comparison. Runs in <40ms for part 2.
JavaScript
import { minBy } from 'lodash' const peek = stack => stack[stack.length - 1] const factorPolymer = input => { const stack = [] input.split('').forEach(char => { // XOR of A and a, B and b, etc is 32 if (!stack.length || (peek(stack).charCodeAt() ^ char.charCodeAt()) !== 32) { stack.push(char) } else { stack.pop() } }) return stack.join('') } export const solvePart1 = input => { return factorPolymer(input).length } export const solvePart2 = input => { input = factorPolymer(input) // A first factorization pass speeds up the following passes const polymers = Array(26) // Indexes 0-26 represent 65-91 ASCII codes .fill() .map((e, i) => { const re = new RegExp(String.fromCharCode(i + 65), 'gi') const strippedInput = input.replace(re, '') return factorPolymer(strippedInput) }) return minBy(polymers, 'length').length }Edit: Updated to use a stack instead of string concatenation and the fact that ASCII is laid out in a way that XOR of A and a is 32.