r/adventofcode • u/daggerdragon • Dec 14 '18
SOLUTION MEGATHREAD -π- 2018 Day 14 Solutions -π-
--- Day 14: Chocolate Charts ---
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 14
Transcript:
The Christmas/Advent Research & Development (C.A.R.D.) department at AoC, Inc. just published a new white paper on ___.
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:19:39!
16
Upvotes
View all comments
Show parent comment
2
u/Smylers Dec 14 '18 edited Dec 14 '18
Congrats on making the leaderboard. My Perl was very similar to yours, but my first βmistakeβ was thinking β2 elves β let's put them in an array so I can iterate over themβ. While that arguably increases the elegance (see the code below), it definitely destroys the performance.
Yours takes 18 seconds to solve Part 2; using an array slows it down to 46 seconds, (with the CPU fan whirring frantically) β long enough for me to cancel it, thinking something was wrong.
Which, handily, it was: my second mistake was thinking β
rindexreturns the last match in a string, so presumably it's optimized to search from the endβ. Apparently it isn't.Using
rindexβ but no arrays β takes those 18 seconds up to, I've now discovered, 9Β½ minutes! (I haven't timed my original combination of both an array andrindextogether.)indexdoes let you provide a starting position as its third argument ((index $recipes, $find, (length $recipes) - (length $find) - 1) >= 0), which makes that fast enough β benchmarking shows no significant difference between that and the pattern-match withpos. I think the pattern-match is more readable:I set
posat the end of the loop, so the loop exit condition can just be at the start, rather than requiring alastcheck in the middle of an apparently infinite loop.It turns out
posaccepts negative values counting from the end of the string, and setting it βtoo negativeβ is harmless (it treats it as0), so you don't need theifguard around it, nor to subtract fromlength $syourself.Update: Forgot the [Card]: βThe Christmas/Advent Research & Development (C.A.R.D.) department at AoC, Inc. just published a new white paper onβ premium 100gsm A4, made from sustainable sources. [They're metric up there.]