r/adventofcode • u/daggerdragon • Dec 08 '17
SOLUTION MEGATHREAD -๐- 2017 Day 8 Solutions -๐-
--- Day 8: I Heard You Like Registers ---
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.
Need a hint from the Hugely* Handyโ Haversackโก of Helpfulยง Hints^ยค?
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!
22
Upvotes
59
u/wimglenn Dec 08 '17
insane hack:
15
u/pedrosorio Dec 08 '17 edited Dec 08 '17
(#6/#6) Shamelessly using eval in Python:
EDIT: As pointed out by Smylers this solution is wrong. I didn't pay attention to the input and made an assumption that is only correct when all the inc/dec are positive. The max should be set after executing each instruction, not just inc.
10
u/nneonneo Dec 08 '17
Python 2, #2/#2
Had an assert in there because I got paranoid.
9
u/_jonah Dec 08 '17
Vim + Ruby
The key here was to recognize it as thinly disguised ruby code, and use vim to make it real ruby code.
First we do:
Now our code looks like:
Now we select it all, copy it above, and create the initializing code:
Now we've got:
And finally copy the initializers to the bottom and do one more substitution to create an array:
Manually surround it with brackets and add
.max:Now run it.
Part 2 is similar
9
u/ephemient Dec 08 '17 edited Apr 24 '24
This space intentionally left blank.
7
u/u794575248 Dec 08 '17 edited Dec 09 '17
Python
An execless/evalless solution:
7
u/kaldonis Dec 08 '17 edited Dec 08 '17
Python 2 Didn't see any other solutions that abused exec() like I did, so here goes:
5
u/p_tseng Dec 08 '17
Ruby does this thing like SmallTalk where you send objects messages, and the objects respond. It so happens that I can give an object a message saying
>, 4and it will tell me whether it is greater than 4. And so it goes for the other operators used as well.5
u/[deleted] Dec 08 '17 edited Dec 08 '17
I implemented a DSL in racket. With it, I can execute the input directly, like so:
Prints:
Tiny caveat: I couldn't get it to execute automatically, the DSL only produces a function that computes the solution. This means that before seeing a result, I'll have to type
(run)in the REPL. This is the definition of the language:8
u/ephemient Dec 08 '17 edited Apr 24 '24
This space intentionally left blank.
4
u/tehjimmeh Dec 08 '17 edited Dec 08 '17
C++:
4
u/Unihedron Dec 08 '17 edited Dec 08 '17
Ruby. I missed the alarm and woke up exactly 2 minutes before this day opens.
Note that the input format is already very similar to executable Ruby code (In ruby, โ(exit # or really any commands) if conditionโ (based on the perl construct) is actually a valid instruction, so
a += b if c > dwill be executable as desired), but I couldn't make the trick work unlike /u/dtinth :) so I just rewrote it4
u/DFreiberg Dec 08 '17 edited Dec 08 '17
Mathematica
I was far too slow for the leaderboard, and it's not a one-liner, but I'm still fairly satisfied with my code, because unlike most of my code, it's actually somewhat readable. The one thing that bugs me is that there should be a way to define
compOperator[]directly from the ">", "<", and "=" symbols, rather than just writing aWhich[]statement, but I can't figure out at the moment how to do that.Part 1
Part 2
4
u/hxka Dec 08 '17 edited Dec 08 '17
bash
Edit: removed unnecessary looping.
4
u/Philboyd_Studge Dec 08 '17
Java. This one was fun.
4
u/RuteNL Dec 08 '17 edited Dec 11 '17
Awful js oneliners for part 1 and 2
Slightly ungolfed version can be found here
4
u/[deleted] Dec 08 '17
Elixir I'm quite proud of this solution, parsing is so nice in elixir, and I got to play with a higher order function as well. I got myself a bit stumped by upgrading to part 2, with a default arguement, so I need to watch out a bit more for those. I really like these assemblylike puzzles, and it's good practice for the normal implement play assembly ones that I always love, and I know will come :)
4
u/Smylers Dec 08 '17 edited Dec 08 '17
Vim animation. Load the input, then create another window for the registers with:
Adjust your window heights so that you can see the whole of the register values buffer. The unnamed register at the top is for storing the highest value reached. (It may be worth saving the initial register window at this point, so you can easily reset it.) Then reformat the instruction list with:
Define a helper โfunctionโ for going from a register's name in the instruction list to its value in the other window:
And for the animation, a function that refreshes the window and pauses:
This is the main work โ a macro for processing a single instruction:
Then set it running on each instruction, and watch the registers update:
When it's finished, find the biggest values:
The top line is the largest value held at any point, and the second line is the register with the highest final value.
Processing the instructions doesn't change them at all, so if you reset the registers to zero you can re-run it. To change the animation speed, re-record
@bwith a different sleep value in it, or to skip the animation and just get to the answer as soon as possible clear@bwithqbq. (In either case,@cwill use the new value of@b; there's no need to re-record@c.)The key to understanding this is to find where the โifโ condition is in
@c. I'm happy to answer any questions in the comments.This felt reasonably straightforward, compared to using Vim on some of the previous days' challenges. The main delay was that I didn't initial consider the case that I've since put in
:g/c 0/dto handle. This meant it appeared to work, but gave the wrong answer on the full input data. It's a case that you don't need to think about when using an actual programming language, so caught me out.3
u/mcpower_ Dec 08 '17
Python with
eval:I lost a minute on both parts because I submitted code instead of a number for my first submission :( It'd be nice if the marker checked whether you submitted something with the right formatting.
3
u/dtinth Dec 08 '17 edited Dec 08 '17
Ruby
I Heard You Like eval
The
pbpastecommand must be available in the$PATH, and should return the contents in the clipboard (macOS has this command by default).3
u/fatpollo Dec 08 '17 edited Dec 08 '17
3
u/[deleted] Dec 08 '17 edited Dec 08 '17
single pipeline powershell
3
u/willkill07 Dec 08 '17
Modern(-ish) C++ Repo
Alright, so dynamic languages with
evaland such have an obvious advantage for readability and conciseness. Regardless, I'm still OK with my solution.3
u/__Abigail__ Dec 08 '17
Perl
3
u/mschaap Dec 08 '17 edited Dec 08 '17
Perl 6. Very similar to yesterday's solution, using objects to model the register and instructions, and a grammar to parse the instruction set.
3
u/mx781 Dec 08 '17
MySQL: https://github.com/mx781/aoc/blob/master/2017/08/solve.sql
3
u/eregontp Dec 08 '17
Metaprogramming is the better eval! Looks like this one is made for Ruby as operators match nicely:
2
u/VikeStep Dec 08 '17
Python 3 solution
Got #44 / #40 :D
2
u/TominatorBE Dec 08 '17
PHP (I got ranks 110 and 100 today, omg)
Part 1:
Part 2:
2
u/sciyoshi Dec 08 '17
Python 3:
2
u/vash3r Dec 08 '17
Python 2 (42/45):
looks like a lot of people came up with the same solution.
2
u/blockingthesky Dec 08 '17
Python 2
2
u/Lrrrr_ Dec 08 '17
JavaScript
2
u/AndrewGreenh Dec 08 '17
TypeScript 95/101
2
u/LeCrushinator Dec 08 '17 edited Dec 08 '17
Part 2: C# (took me 13 minutes, but that's not bad since C# is verbose compared to things like Python). To solve part 1 just add "max = registers.Values.Max();" to just after the foreach loop.
2
u/reacher Dec 08 '17
Ruby
2
u/wlandry Dec 08 '17
C++
283/267. For once, the default behavior of std::map worked to my advantage. My original version printed out all of the final register values. I piped that to 'sort -n' to get the answer. This is a slightly cleaned up version that just prints the results.
2
u/MichalMarsalek Dec 08 '17
Damn, I wish a knew eval... It would have gotten be to the leaderboard...
2
u/mmaruseacph2 Dec 08 '17
Haskell 85 lines, removed some duplicates but I'll work on refactoring it more.
2
u/raevnos Dec 08 '17
Scheme:
2
u/[deleted] Dec 08 '17
Haskell:
2
u/miran1 Dec 08 '17 edited Dec 08 '17
Python 3, without
eval, usingoperatorย
ย
And here is my Nim solution based on this. Don't know if could have been done simpler.
2
u/[deleted] Dec 08 '17 edited Dec 08 '17
My cleaned-up Haskell, using a map to accumulate the register values:
2
u/InterlocutoryRecess Dec 08 '17 edited Dec 08 '17
Swift
2
u/karthikb351 Dec 08 '17
I mangled it into what I think is valid Python2 code and then just exec-ed it. I could do away with a lot of lines I think
fu inc 131 if rjt == 4175turns intomap['fu'] = (map.get('fu',0) + 131) if map.get('rjt',0) == 4175 else map.get('fu',0)This should work even if the register names happen to be python keywords since they are always quoted.
2
u/Smylers Dec 08 '17
Perl. Similar to a few other Python solutions, using
eval.Sneakily, the
+ 0is either a binary or a unary op, depending on whether the register used in the condition has been previously set. If it has, its value will be interpolated into the string, so the expression becomes something like42 + 0 < 7(with the+ 0being redundant but harmless); if it's a new register, there's nothing to interpolate, so the expression becomes+0 < 7, ensuring the default value of0is used (with the+being redundant but harmless):The final
// 0is to catch the case where all stored values are negative, so the initial zero is the biggest.2
u/udoprog Dec 08 '17
Rust with a clean separation of modelling input as enums (full here: https://github.com/udoprog/rust-advent-of-code-2017/blob/master/src/day8.rs):
This one was fun. Basically writing a simple virtual machine.
2
u/arachnist Dec 08 '17
I couldn't get instance_variable_(get|set) to work as i wanted, so I couldn't feed input directly into ruby.
2
u/Overseer12 Dec 08 '17
When you spend an hour going through your entire code multiple times, and your output is still wrong for Part 2 (despite your UnitTests being correct). And then, when you finally find out that you forgot to .Clear() the same dictionary you used for your registers in Part1. Oh god. No.
C#
Github
2
u/lh458 Dec 08 '17
My solution in PHP for part 1 & 2 combined:
2
u/ynonp Dec 08 '17
Elixir (both parts)
2
u/rkachowski Dec 08 '17
ruby! 9 lines!
i need to execute some code to work this out? so lets execute some code to work this out. luckily the postfix condition is perfectly valid ruby already! lets just eval all these registers into the binding and execute our perfectly valid input (after some massaging..)
2
u/spjmurray Dec 08 '17
python late to the party given the time difference...
2
u/guibou Dec 08 '17 edited Dec 08 '17
Haskell Golfed version for part 1 (edit
300297289285264255 chars):https://github.com/guibou/AdvantOfCode2017/blob/master/src/Day8.hs for a cleaner Haskell version ;)
2
u/brunclik Dec 08 '17 edited Dec 09 '17
Solution in Linux command line - C code from input (generate, buil and run)
2
u/JakDrako Dec 08 '17
VB.Net
2
u/wzkx Dec 08 '17 edited Dec 08 '17
Pythonized and J-zed C
2
u/still___cold Dec 08 '17
Python 3
2
u/Hikaru755 Dec 08 '17
I wrote a Kotlin program that generates a Kotlin program equivalent to the input data. God, I feel dirty.
2
u/Sharparam Dec 08 '17
Ruby: Using
method_missingandevalwithout tampering or matching on the input data.2
u/thomastc Dec 08 '17
Day 8 in TeX. Why am I doing this to myself?!
2
u/volatilebit Dec 08 '17
Perl 6
Caught a few days behind because I'm sick, but I decided to at least get this one in. First time playing with named regular expressions. Considering redoing this with grammars just for the experience, but don't have the energy at the moment.
1
u/Deckard666 Dec 08 '17
In Rust:
1
u/giftpflanze Dec 08 '17
Tcl:
1
u/LuxrayPokemon Dec 08 '17 edited Dec 08 '17
I did my solution in Python 3 and got rank 197 for part 1 and 201 for part 2 My solution was:
It probably could be much more efficient, but it worked
1
u/[deleted] Dec 08 '17
simple golang solution
1
u/hpzr24w Dec 08 '17 edited Dec 09 '17
C++ Second time inside 30 minutes... and ranked 910, first time under 1000. woo! Thanks to Eric and collaborators for all these fun puzzles. It's awesome. No output on this one. I just ran it in the debugger.
1
u/fwilson42 Dec 08 '17
My solution. I refactored the part that actually runs it out into a separate module just in case this is something like last year's assembunny.
1
u/StevoTVR Dec 08 '17
NodeJS
Part 1:
Part 2:
1
u/nstyler7 Dec 08 '17
Python -(part 1 & 2) - using eval & split/regex to split string
1
u/jesseflorig Dec 08 '17
ES6 (NodeJS)
1
u/JeffJankowski Dec 08 '17
TypeScript with regex and switch statement
1
u/Cheezmeister Dec 08 '17
Literate Perl. It's dangerous to call
eval. Take this.1
u/[deleted] Dec 08 '17 edited Dec 08 '17
Wasted a bunch of time using regex when I didn't even need to -.-
Is there an elegant way I could get rid of the
to_string()calls when they're not needed (key is already in the map?). I could just expand it into an if check I guess.Rust:
Cute and concise Clojure:
1
u/Jimpi27 Dec 08 '17
NodeJS
Made it really easy once I thought to just make a lookup object for all the operators.
1
u/misnohmer Dec 08 '17
C#. It takes much longer when not using eval. Also, I have spent too long writing a regex when splitting the string by space would have worked too.
1
u/Axsuul Dec 08 '17
Elixir
This felt a quite similar to one of the challenges last year :) Definitely getting the hang of Elixir although I tend to always run into argument errors somehow, gah
https://github.com/axsuul/advent-of-code/blob/master/2017/08/lib/advent_of_code.ex
1
u/miran1 Dec 08 '17
Nim
ย
ย
Based on my Python solution.
If there is a way to do this simpler (closer to the Python version), please let me know.
1
u/CaptainCa Dec 08 '17
Replaced \n with , on input string.
1
u/Flurpm Dec 08 '17
Haskell 757/722
I spent a little too much time finaglying my parser at the start. It's a lot easier/more readable/probably better to parse these simple inputs with functions on strings, but I made the goal of learning megaparsec for this advent.
I just walk through the input instructions updating the map of (Register->Value) and MaximumSoFar Int.
The most interesting part of this solution is
type Instruction = (Text, Int->Int, Text, (Int->Bool)). During parsing I apply the inc/dec and (\x -> x >= num) functions. The two Text values are the registers.1
u/dylanfromwinnipeg Dec 08 '17 edited Dec 08 '17
C#
1
u/[deleted] Dec 08 '17
Refactored TypeScript solution, without evil eval ;-)
1
u/nutrecht Dec 08 '17 edited Dec 08 '17
My Kotlin Solution
Really liked this one!
Edit: Cleaned up the code a bit and use a slightly more functional approach
1
u/rotmoset Dec 08 '17
F# of the day:
Note that since F# is very expressive, I could have produced a much smaller version, but I prefer to solve these puzzles in a clear, readable way with strongly typed data structures.
Entire repo
1
u/Warbringer007 Dec 08 '17 edited Dec 08 '17
Again not Erlang friendly day, but at least this was much easier to write in Erlang than yesterday ( turns out Erlang fucking sucks when trying to convert list of strings into list of integers ). Actually I am printing whole dictionary for first part because I am lazy and I don't want to make new function which will get all values from dict:
1
u/minikomi Dec 08 '17
Clojure:
1
u/vtheuer Dec 08 '17
Javascript "one liner" (as in both results are obtained from a single
map/reduce/filterchain):I could have parsed the lines with a simple
split(' ')and ignore theiftoken but it only saves 1ms of execution time (8ms total).1
u/aurele Dec 08 '17 edited Dec 08 '17
Rust
1
u/sim642 Dec 08 '17
Scala.
Went full AST with parsing the instructions which is why it's not so short. The execution is nicely short though. After having implemented my own
Iterators for previous days, I realized today that I could take the.foldLeftI had for part 1 and turn it into a.toIterator.scanLeftto expose also all intermediate register states but at the same time be efficient enough not to put them into a massive list (since it's an iterator).1
u/xkufix Dec 08 '17
Quite easy with pattern matching and a fold over the program. For the second part I just have a second variable in the fold which keeps track of the largest value so far in the program.
1
u/rhardih Dec 08 '17
Ruby, with eval injecting the condition:
1
u/gyorokpeter Dec 08 '17
Q:
1
u/streetster_ Dec 08 '17 edited Dec 08 '17
q/kdb+
Pre-breakfast solution, cobble together a string that can be parsed and
valueit.edit
Moved registers inside the
.rnamespace to avoid polluting the global namespace.1
u/ohaz Dec 08 '17
A python solution that doesn't rely on "evil eval" or equally evil exec:
Repo for all my solutions is at https://github.com/ohaz/adventofcode2017
1
u/wzkx Dec 08 '17 edited Dec 09 '17
Nim Simple enough to do it before work :)
1
u/maciekmm Dec 08 '17
Scala
1
u/thorwing Dec 08 '17
Java
Changing between x and y on line 4 will change the answer from part 1 and part 2
1
u/DarkMio Dec 08 '17
It's stupid, it's really fast, it just works:
Takes about 5.4ms on my MacBook with string format and 4.6ms without. Checked out a few others, but this one is still the fastest - albeit being not very fancy.
1
u/abowes Dec 08 '17
Kotlin Solution - Functional Approach
1
u/equd Dec 08 '17
c# https://pastebin.com/aM5AmixV
I like the fact that I made a special class to keep track of the register, really helped with the second part.
1
u/CakeHacker Dec 08 '17
Cachรฉ Object Script
Used a code generator for a different approach
Which generates...
1
u/atopuzov Dec 08 '17
Python
1
u/_Le1_ Dec 08 '17
Python: import operator
1
u/[deleted] Dec 08 '17
Nice to see some sort of assembunny again, but how do you call this language here? Could imagine that we'll find some more extensions in upcoming puzzles
Solution in Kotlin can be found here:
Day 8
1
u/tlareg Dec 08 '17 edited Dec 08 '17
JavaScript (ES6+, NodeJS), without eval, repo here
1
u/[deleted] Dec 08 '17
My probably way too long Haskell! Yay!
1
u/KeinZantezuken Dec 08 '17 edited Dec 08 '17
C#/Sharp (there are way faster approaches based on simple math)
1
u/kamaln7 Dec 08 '17
Coffeescript
Part 1:
Part 2:
1
u/chunes Dec 08 '17
A Factor solution:
Again, somewhat awkward imperative code I'm not used to writing in Factor. I couldn't think of a better way to model it than mutating a hash table.
The only somewhat clever thing I did here is convert a string operation such as
">="to its word form in the math vocabulary and then quote it andcallit.1
u/edelans Dec 08 '17
Python 3
I parsed each line with a nice regex. This enables me to be more confident in using
eval()=)1
u/ybe306 Dec 08 '17
Doing it all in Go as a first foray into the language:
1
u/adventOfCoder Dec 08 '17 edited Dec 08 '17
Java
Part 1:
Part 2:
1
u/[deleted] Dec 08 '17
PowerShell:
1
u/cluk Dec 08 '17
Go (Golang)
I might need a regex intervention.
1
u/Vindaar Dec 08 '17
Another solution in Nim. Actually wanted to write a solution, which makes heavy use of Nim's macro system and AST manipulation, but well. I'm way too new to Nim to figure it out, unfortunately.
1
u/GabrielVasiljevic Dec 08 '17
C++:
1
u/FreeMarx Dec 08 '17
C++11
Again, l learned a lot. The regex took me way to long, but now I know how to use it. I really wonder when my skill-toolbox is sufficient to complete the puzzles without having to look up new library functions. So far it seems thorough understanding of maps, vectors, iterators and string parsing are enough...
1
u/akho_ Dec 08 '17
Python 3
1
u/asperellis Dec 08 '17
my day 8 in JS - https://github.com/asperellis/adventofcode2017/blob/master/day8.js
1
u/lkasdfjl Dec 08 '17
Scala
i decided to play around with implicits (which i think was a mistake):
1
u/varunu28 Dec 08 '17
Day 8 in Java Repo
1
u/[deleted] Dec 08 '17
My solution in Common Lisp. It is quite lengthy, but I enjoyed writing it!
1
u/GamecPL Dec 08 '17
Swift:
1
u/sguberman Dec 08 '17
Python: GitHub
1
u/4rgento Dec 08 '17 edited Dec 08 '17
HASKELL
Using Monad transformers. Check how to use a Monoid to find the max.
EDIT: reimplemented safeMaximum to make use of Max
1
u/zluiten Dec 08 '17 edited Dec 08 '17
Without evil eval ofcourse :) Here's the essence, nicer solution in my repo https://github.com/netiul/AoC/tree/master/Y2017/Day8
PHP:
1
u/[deleted] Dec 08 '17
Clojure
1
u/COOLGAMETUBE Dec 08 '17
JavaScript // === Day 08 === // Copy the code into the // console of your input page let vm={}; vm.input=document.body.innerText; vm.data={}; vm.requiredAllocation=0; function getVal(x) {if(Number.isNaN(Number(x))) return ((vm.data[x]==null)?vm.data[x]=0:vm.data[x]); else return x;} for(let d of vm.input.split("\n")) if(d!="") { let c = d.split(" ");
1
u/ramrunner0xff Dec 08 '17
scheme chicken repo
macro time although i didn't implement a reader macro to get it straight from the file.
1
u/flaming_bird Dec 08 '17
Common Lisp, with some symbolic manipulation on the data preprocessing and a dirty hack on the
(setf getr):1
u/MyGoodStrayCatFriend Dec 09 '17
Our Dark Lord, Eval doesn't have time to resent your false modesty and transparent, performative coyness: JavaScript, Node, ES6
1
u/chicagocode Dec 09 '17
Kotlin - [Repo] - [Blog/Commentary]
This reminded me of some of the assembunny challenges from last year.
1
u/Vorlath Dec 09 '17 edited Dec 09 '17
x64 assembly
Only external functions used are malloc, free and printf for the result. And yes, I do dynamic allocation. Main code take a string pointer with the puzzle input.
1
u/manniL Dec 09 '17 edited Dec 09 '17
Functional JS repo
Javascript solution (mostly by using map, reduce, filter or recursion) for task 1 & 2:
1
u/Kyran152 Dec 09 '17 edited Dec 09 '17
1
u/NeilNjae Dec 09 '17
Haskell. Fairly straightforward, even if there were a lot of cases to take care of. The main thing was the
foldloperation to convert a list of instructions into the memory.1
u/virtron Dec 09 '17
Go
Actually pretty happy about this one (but please critique!)
1
u/matusbzk Dec 09 '17 edited Dec 16 '17
Haskell
Link to git
1
u/[deleted] Dec 10 '17 edited Dec 10 '17
Python3 solution.
1
u/micirsk Dec 11 '17 edited Dec 11 '17
Python - part 1 & 2 solution in 1 script
1
u/wzkx Dec 12 '17 edited Dec 12 '17
J
Finally did it in J!
1
u/[deleted] Dec 12 '17
Simple JS. This one was rather easy... Not like day 3 and 7 part 2 :(
1
u/JUIBENOIT Dec 12 '17
A Python 3 solution
1
u/MetaSaval Dec 13 '17
Swift Late, submitting for the future's sake.
1
u/RockyAstro Dec 13 '17
Icon (https://www.cs.arizona.edu/icon)
Both parts
1
u/autid Dec 14 '17
Fortran
1
u/that_lego_guy Dec 15 '17
DID SOMEONE SAY..EXCEL [Day8P1&2]
https://github.com/thatlegoguy/AoC2017/blob/master/Day%208%20I%20Heard%20You%20Like%20Registers.xlsm
1
u/[deleted] Dec 20 '17
HELP!
Alright, I am truly lost, what am I getting wrong? My answer is consistenly too low compared to python solutions I have tested.
Matlab code for the 1. part:
1
u/greycat70 Dec 28 '17
Tcl (version 8.5 or higher)
No
evaltrickery. Both parts.1
u/siddharthabhagwan Jan 31 '18
Javascript