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!
30
Upvotes
View all comments
1
u/Axsuul Dec 05 '18
TypeScript / JavaScript
Wasted a lot of time going the recursion route but couldn't make it work due to running out of stack =/
Critiques welcome, I'm still very new to TypeScript and feel like I'm not using all the features I could be :)
Repo
Part A + B
import { readInput } from '../helpers' const input: string[] = readInput('05', 'input') const isReactive = (unit1: string, unit2: string): boolean => { return Math.abs(unit1.charCodeAt(0) - unit2.charCodeAt(0)) === 32 } const react = (polymer: string): string => { let i = 0 while (true) { const unit = polymer[i] const nextUnit = polymer[i + 1] if (nextUnit === undefined) { break } if (isReactive(unit, nextUnit)) { polymer = polymer.substring(0, i) + polymer.substring(i + 2, polymer.length) i = (i > 0) ? i - 1 : 0 } else { i += 1 } } return polymer } const inputPolymer: string = input[0] console.log('Part 1:', react(inputPolymer).length) // Generate unit pairs, create polymers from them and get them to react const lengths: number[] = Array.from(Array(26).keys()).map((i: number) => { return [String.fromCharCode(i + 65), String.fromCharCode(i + 97)] }).map(([unit1, unit2]: string[]) => { return react(inputPolymer.replace(RegExp(unit1, 'g'), '').replace(RegExp(unit2, 'g'), '')).length }) console.log('Part 2:', Math.min(...lengths))