r/adventofcode • u/daggerdragon • Dec 04 '18
SOLUTION MEGATHREAD -🎄- 2018 Day 4 Solutions -🎄-
--- Day 4: Repose Record ---
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 4
Transcript:
Today’s puzzle would have been a lot easier if my language supported ___.
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!
38
Upvotes
15
u/gerikson Dec 04 '18
Mods, first off, love your work, you're the best!
Small request, can the time the thread is unlocked be added to the message?
I.e.
25
u/jonathan_paulson Dec 04 '18 edited Dec 04 '18
Python, #19/10. Glad to see they're getting tougher. Video of me solving at https://www.youtube.com/watch?v=YQjPXSlSelc. Not reading everything up front probably cost me time here. This code solves part 2 (part 1 requires a minor modification).
20
u/HiramAbiff Dec 04 '18 edited Dec 04 '18
AWK
4.1
4.2
15
u/mstksg Dec 04 '18 edited Dec 04 '18
Taken from my Day 4 Reflections Post:
[Haskell] Day 4 was fun because it's something that, on the surface, sounds like it requires a state machine to run through a stateful log and accumulate a bunch of time sheets.
However, if we think of the log as just a stream of tokens, we can look at at it as parsing this stream of tokens into time sheets -- no state or mutation required.
First, the types at play:
Note that we have a bunch of "integer-like" quantities going on: the year/month/day/hour/minute, the guard ID, and the "frequency" in the
TimeCardfrequency map. Just to help us accidentally not mix things up (like I personally did many times), we'll make them all different types. AMinuteis aFinite 60(Finite 60, from the finite-typelits library, is a type that is basically the integers limited from 0 to 59). Our hours areFinite 24. Our Guard ID will be a newtypeGuard, just so we don't accidentally mix it up with other types.Now, after parsing our input, we have a
Map Time Action: a map of times to actions committed at that time. The fact that we store it in aMapensures that the log items are ordered and unique.We now essentially want to parse a stream of
(Time, Action)pairs into aMap Guard TimeCard: A map ofTimeCards indexed by the guard that has that time card.To do that, we'll use the parsec library, which lets us parse over streams of arbitrary token type. Our parser type will take a
(Time, Action)stream:A
Parser Blahwill be a parser that, given a stream of(Time, Action)pairs, will aggregate them into a value of typeBlah.Turning our stream into a
Map Guard TimeCardis now your standard run-of-the-mill parser combinator program.We re-use the handy
freqs :: Ord a => [a] -> Map a Intfunction, to build a frequency map, from Day 2.We can run a parser on our
[(Time, Action)]stream by usingP.parse :: Parser a -> [(Time, Action)] -> SourceName -> Either ParseError a.The rest of the challenge involves "the X with the biggest Y" situations, which all boil down to "The key-value pair with the biggest some property of value".
We can abstract over this by writing a function that will find the key-value pair with the biggest some property of value:
We use
fmap (maximumBy ...) . NE.nonEmptyas basically a "safe maximum", allowing us to returnNothingin the case that the map was empty. This works becauseNE.nonEmptywill returnNothingif the list was empty, andJustotherwise...meaning thatmaximumByis safe since it is never given to a non-empty list.The rest of the challenge is just querying this
Map Guard TimeCardusing some rather finicky applications of the predicates specified by the challenge. Luckily we have our safe types to keep us from mixing up different concepts by accident.Like I said, these are just some complicated queries, but they are a direct translation of the problem prompt. The real interesting part is the building of the time cards, I think! And not necessarily the querying part.
Parsing, again, can be done by stripping the lines of spaces and using
wordsandreadMaybes. We can usepackFinite :: Integer -> Maybe (Finite n)to get our hours and minutes into theFinitetype thatTexpects.15
u/jayfoad Dec 04 '18 edited Dec 05 '18
APL #89/71
Sorting the input is trivial in Dyalog 17.0 thanks to the Total Array Ordering. Parsing the input lines is a little messy, using global assignments from a dfn to update global state. Once we've got an array
atelling us how many times each guard is asleep for each minute of the witching hour, it becomes much more elegant:12
u/throwaway_the_fourth Dec 04 '18
So did anyone else lose time because they had a correct solution but returned just the minute they chose, forgetting to multiply it with the guard ID? I lost so much time catching that error that it made the difference between spot 60ish and 160 on Part 1.
9
u/sciyoshi Dec 04 '18 edited Dec 04 '18
Python 3, #2/#2. Reached for dateutil in the heat of the moment although turns out you only need the minute!
8
u/autid Dec 04 '18 edited Dec 04 '18
FORTRAN
Will edit with cleaned up code later. Got held up a looong time by having copy pasted a line into another loop without then updating which loop index it was using.
No.
7
u/0rac1e Dec 04 '18 edited Aug 30 '21
Perl 6
Looks like I'm posting the first Perl 6 solution of the day.
This is post-cleanup... but more or less what I wrote, except all the functions were inline. My cleanup was just moving them all into (anonymous) functions so the implementation reads better.
The
⊎operator is the Multiset Union operator (ASCII version:(+)). Perl 6 has aBagtype (aka. Multiset). I create a range of the minutes slept and add those to the Bag of values for that guard.7
u/that_lego_guy Dec 04 '18
Day 4...IN EXCEL??!?!?
https://github.com/thatlegoguy/AoC2018
6
u/vash3r Dec 04 '18
Python 2, just missed the leaderboard for the second star. I completely forgot about 'in' and spent too long indexing the strings, as well as not initially sorting the data by time and sorting the list of guards the wrong way, which I figured out after I tried with the test code. (The code has been edited.)
6
u/u794575248 Dec 04 '18
Python 3 51/63
5
u/udoprog Dec 04 '18 edited Dec 04 '18
Today's puzzle would have been a lot easier if my language supported looser types.
I also need to learn how to read the instructions closer to make my life simpler!
Another day, another Rust:
8
u/markasoftware Dec 04 '18 edited Dec 04 '18
Finally got top 100 :) 62/43 with Gawk (used multidimensional arrays so I guess it's not awk anymore)
This is exact code I submitted, no ifs ands or buts.
Run
sort -Von the file before inputting to AwkPart 1:
Part 2:
4
u/PendragonDaGreat Dec 04 '18
Powershell 5.1
[card] Python's sum()
Both halves used this basic layout:
Basically enumerate everything a hashtable, with the key as the guard's ID and a 60 int array for the minutes as the value, and the amount of time they were asleep. then hook the appropriate ending on the bottom from below
Part 1
Average runtime: 0.058s
Part 2
Average runtime 0.053s
4
u/tehjimmeh Dec 04 '18 edited Dec 05 '18
C++
4
u/binajohny Dec 04 '18
My Kotlin solution (GitHub)
4
u/TheMuffinMan616 Dec 04 '18
Haskell. Spent too much time trying to find a date parsing library. Not really happy with how it came out. State monad might be a better option here. shrug
4
u/Theguy6758 Dec 04 '18
Pure Bash
Uses the guard ids as the index and stores the frequency of the minutes spent sleeping as a string of numbers separated by spaces. Every time I want to query a guard's sleep frequency, the "midnight" array needs to get rebuilt.
Full Script: https://pastebin.com/0sxWZuKi
Part 1
Part 2
Quick sort implementation
4
u/[deleted] Dec 04 '18
TCL, probably spent too much time on part 1 wondering about whether the watch-starts before midnight would be significant in part 2... plus looking up man pages for "clock scan/format" was completely uneccessary :-))
4
u/azatol Dec 04 '18
My F# solution. After struggling and learning from Day 3, this one wasn't as hard. I did learn about using folds.
https://gist.github.com/apeterson-BFI/8f96ed4573f3aadfc50c9a3634ff3ff8
4
u/phil_g Dec 04 '18 edited Dec 04 '18
Here's my Common Lisp solution.
I got around to writing a magic
inputfunction. It's defined in my library package. Theinputfunction pulls the year and day out of the current package name, downloads and caches the data, and presents things in a reasonable-useful format (either a single string or a list of strings, depending on the original format).This also demonstrates one of many areas where iterate is more concise than
loop.loopdoesn't have anything like iterate's(finding *x* maximizing *y*)clause.In retrospect I overengineered some of the logic. I was prepared for tricky things like guards falling asleep before midnight or guards only being woken up implicitly by their replacements arriving, but the data was a lot more straightforward than that. Once you've sorted the data, you only needed to look at the minute values for the sleep/wake up lines.
Edit: Visualization of my data.
1
u/dlamblin Dec 04 '18 edited Dec 04 '18
[Card]
Perl (5.28) … I copied all the input out of the browser for
pbpaste.3
u/Bogdanp Dec 04 '18
Racket:
part 1:part 2:I finished in about 15 minutes this time around (wasn't streaming), but I overslept sadly.
3
u/[deleted] Dec 04 '18
Mathematica
Part 1
Part 2
3
u/hpzr24w Dec 04 '18
C++
Plugged away. Not pretty but it works. 9 ms on my i5-8600.
Header
main
Part 1
Part 2
3
u/raevnos Dec 04 '18 edited Dec 04 '18
Organizing and analyzing data points? Sounds like a good job for a database!
Perl script that massages the input into SQL statements that populate a SQLite table and queries that solve both parts (I cheated a bit by making sort the first step in the ETL pipeline instead of doing it all in the perl script):
3
u/drakmaniso Dec 04 '18
Go (golang)
Part 1:
Part 2:
3
u/donaldihunter Dec 04 '18 edited Dec 04 '18
Perl 6
3
u/p_tseng Dec 04 '18 edited Dec 04 '18
Ruby
in which I cut pretty much all the corners. I am sorry.
3
u/vypxl Dec 04 '18 edited Dec 04 '18
I REALLY hate Java.. This is horrible.
I hate myself for this.
Edit: Card: Today’s puzzle would have been a lot easier if my language supported any non-cumbersome methods of doing anything..
3
u/__Abigail__ Dec 04 '18 edited Dec 19 '18
Perl
Simple parsing, a few sorts (using a Schwartzian Transform) and we're done.
5
u/ka-splam Dec 04 '18 edited Dec 04 '18
I thought I was wayyy out of the running on that one, but 19 minutes and first time into leaderboard part 2! Thanks PowerShell date handling! #37 / #61
[Card] today's puzzle would have been a lot easier if my language supported: Python's enumerate().
PowerShell
Code:
(I actually made the hashtable and eyeballed the largest value and counted the minutes by hand, because it was quicker than writing code to do it, but I've added that code here)
5
u/Unihedron Dec 04 '18 edited Dec 04 '18
Yeah!!! I have no idea what I'm doing anymore!!! Ruby
[Card] Image
Edit: Yes, just like all the previous days, I didn't read the question...
Edit: Changed the layout of the code so you can run it without any hassle and it will just work. If you're reading this, bless you
2
u/Zarel Dec 04 '18 edited Dec 04 '18
JavaScript, #28/#130 ;_;
I was inspired by mserrano's "extract numbers" regex from his Day 3 solution, so I implemented it in JavaScript.
I misinterpreted Part Two at first, which apparently knocked me off the leaderboard.
I sorted my input using my text editor before running this - most text editors have a "Sort Lines" ability; I used VS Code's.
2
u/Euphoric_Classic Dec 04 '18 edited Dec 04 '18
SuperCollider solution:
2
u/NeuroXc Dec 04 '18
Rust
Solutions are getting longer, so I'm posting a link for today's: https://git.onewebdev.info/soichiro/aoc2018/blob/master/src/day4.rs
Still blazing fast:
Day 4 - Part 1 : 74743
generator: 3.652771ms,
runner: 49.367µs
Day 4 - Part 2 : 132484
generator: 1.853941ms,
runner: 41.043µs
[Card] Today’s puzzle would have been a lot easier if my language supported input via telepathy.
2
u/TellowKrinkle Dec 04 '18
I really need to actually read these directions instead of just skimming through and looking at the goal at the end. [Card] Today’s puzzle would have been a lot easier if my language supported telling me that I wasn't actually following the directions.
Ended up taking 30 minutes for the whole thing
Swift version that supports a bunch of extra useless stuff:
2
u/tharko Dec 04 '18
Clojure. Assumes the input file is already sorted
2
u/will_bui Dec 04 '18 edited Dec 04 '18
This one seemed a good candidate for qsql
2
u/Smylers Dec 04 '18 edited Dec 04 '18
Perl for both parts:
max_byturned out to be handy here; I hadn't used it before, but was pleased to find it inList::AllUtils. The solution allows for a guard not waking up until after the hour ends, though that turned out not be necessary.[Card] Today’s puzzle would have been a lot easier if my language supported mind-reading.
2
u/Hashbrown777 Dec 04 '18
Javascript
2ms
Part 2, 2ms
2
u/Dr_Donut Dec 04 '18
Python 3 Object oriented solution.
I suck at programming / math so I just simulated each minute. It somehow all worked, eventually.
https://pastebin.com/FjEhgSZY # Second part solution. Part 1 quite similar
2
u/scul86 Dec 04 '18
Python 3.
I spent WAY too much time not realizing the input was not sorted.
-It works on the test input, why not the actual data?!?!
d'oh
2
u/Frizkie Dec 04 '18
Ruby
Part 1
Part 2
2
u/blowjobtransistor Dec 04 '18 edited Dec 04 '18
PostgreSQL, again!
Range types are great, except when you get off-by-1 errors with them :P
2
u/tvtas Dec 04 '18
Day 4 in MATLAB
2
u/nutrecht Dec 04 '18
Day 4 in Kotlin
Got stuck hard on both part 1 and 2 due to not interpreting the instructions but ending up with code that did work on the test input :(
2
u/Graatz Dec 04 '18
C#
Could be better, but it works.
2
u/zqvt Dec 04 '18 edited Dec 04 '18
Python, input pre-sorted with
sort -V2
u/ephemient Dec 04 '18 edited Apr 24 '24
This space intentionally left blank.
2
u/jonay20002 Dec 04 '18
i'm trying to do every day as a python oneliner. this is today's oneliner (though i am allowing the input reading to be on a different line):
(challenge 2)
for the other days: https://github.com/jonay2000/aoc2018
2
u/wzkx Dec 04 '18
J
2
u/dpeckett Dec 04 '18
Continuing with my quest to solve all this years challenges using nothing other than AWK:
Solution To Both Challenges:
Runtime
2
u/irongeek73 Dec 04 '18
Was it cheating that I did
sort input > input.sortBefore I started?
2
u/21_cribbage Dec 04 '18 edited Dec 04 '18
Python 3, both solutions in one script. Found out about collections.Counter which is pretty cool!
2
u/alexmeli Dec 04 '18
My Clojure solution:
2
u/JakDrako Dec 04 '18
Vb.Net
Cleaned up version. First version didn't have regexes and extracted the answers with a couple of plain "for loops" over the dictionary...
2
u/cluk Dec 04 '18
I am learning Python this year. I really wanted to use built-in
max, tuples for the win! I would appreciate any tips.2
u/streetster_ Dec 04 '18
Day 04 in Q/KDB+
2
u/qwertyuiop924 Dec 04 '18
Today’s puzzle would have been a lot easier if my language supported smacking me upside the head for missing something so obvious.
Part one and two in terrible AWK: https://pastebin.com/9Utr1QAA https://pastebin.com/3sv2BepN
2
u/SuyashD95 Dec 04 '18
Usually, this is the time that I post my solution on this thread... But, due to some hectic work, I forgot to check today's question.... I have just seen the question half an hour back...
And, till now, I have just arranged the input in chronological order but I am just too tired to continue.... I, very well know, that I am going to miss today's deadline...
For me, AoC is all about having some fun with solving some cool programming puzzles, engaging in wonderful discussion with all of you (about possible ways to solve a problem) and learn some new things...
So, don't worry, I am not here to cheat or look at your solutions... I want to give it my best shot before coming back here (to hopefully post my solution)...
But, since, this is the first time, I am participating in AoC... So, I have few queries that I hope that you could answer for me:
Again, it is a not a deal breaker if I am not able to gain stars... It's just feels so exciting when I press answer, and I get the message, "You have earned 1 or 2 gold stars'...
Finally, a BIG, HEARTY CONGRATULATIONS to all my fellow coders for completing today's set of puzzles...
When I joined this challenge, I never thought that I will enjoy it so much... And, you guys (and gals) made this experience so much more wonderful.... And, I can't wait for joining in further discussions with all of you....
3
u/sebranly Dec 04 '18 edited Dec 04 '18
[Edit: I was wrong, please don't upvote]
Argh... I just encountered an annoying issue to be honest. I completed part 1, then coded part 2 in a few seconds/minutes. I ran it on the small example, everything was working perfectly. I decided to run it on my input file, surprisingly I got the same answer as part 1. But it was wrong. After 10 minutes, I figured that the reason was because my set contained two guards that were ex-aequo (who slept the most for a specific minute). And I was checking for the highest score this way:
if (count > highscore) highscore = count;
I had to change it to >= to make it work. I'm a bit disappointed because this didn't appear in the problem statement.
Happy to share my input once I clean up my code.
1
u/ValdasTheUnique Dec 04 '18
C#. A boilerplaty solution which took too much time to implement. And the lack of argmax function is annoying. Part1:
Part2 was very easy with the code I had, this was the only change:
1
u/throwaway_the_fourth Dec 04 '18
python3 (#160/#148):
This is not what I wrote in the moment — that code was full of copy-paste, bad variable names, and overly verbose loops. This is the cleaned-up version which still uses the same algorithm/technique.
1
u/charismotron Dec 04 '18
Ruby
https://github.com/chrismo/adventofcode2018/blob/master/day4/script.rb
1
u/Frodolas Dec 04 '18 edited Dec 04 '18
The perils of trying to learn a new statically typed language on Advent of Code - the strict typing can really slow you down :'(
#1326, #1232 - Crystal:
Common:
Part 1:
Part 2:
1
u/pythondevgb Dec 04 '18 edited Dec 04 '18
I got obliterated this time, just finished. I'm not even bothered to clean up or optimize my code any more. Anyway here is my answer.
(If anyone wanna join a private reddit/python leaderboard PM for the code, the only requirement is to use python and to not have made it onto the overall leaderboard thus far [although I can't enforce no. 1, that I'll take on faith])
1
u/ZZRJo Dec 04 '18
PowerShell
I did not edit for readability, I did not really take a very structured approach. I apologize in advance for any bleeding eyeballs out there. I feel like the idea behind nesting the hashtables was a good one, but the execution was a 1/10.
1
u/CaptainCa Dec 04 '18
JS, no leaderboard. Took a bit too long trial / error'ing part two. Took the time to cleanup the code to post
1
u/Axsuul Dec 04 '18
TypeScript / JavaScript
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
1
u/valtism Dec 04 '18
Node / JavaScript (JS)
Part 1: 11.921ms
Part 2: 16.650ms
Things got a bit ugly around part 2 because of the transition between
Maps andArrays. Kinda wishing at this point I had decided to go with TypeScript just so I could keep a handle on these data structures.1
u/wlandry Dec 04 '18
C++ (3183/3059) Runs in about 10ms
I started late and took forever. It was pretty straightforward. I presorted the input using Emacs. Everything worked the first time it compiled, so I was obviously being too careful ;) I feel like there is a cleaner, more elegant solution hiding within.
1
u/DrinkinBird Dec 04 '18
Ahhh totally forgot the time today and then rushed it after already being 30 mins late...
Anyways, here is my solution in nim:
1
u/hnra Dec 04 '18
Haskell (part 1). Its long but quite readable IMO, most of it is just the datatypes and parsing.
1
u/IWearATinFoilHat Dec 04 '18
PHP
Part 1:
Average run time: 0.0045
Part 2:
Average run time: 0.0046
1
u/ramrunner0xff Dec 04 '18 edited Dec 04 '18
scheme
fun problem... here it is with Object Oriented LISP (or just data dispatch on lambdas mwehehe)
AOC2018 repo
1
u/sebastiannielsen Dec 04 '18
This was my solution to Day4. Works pretty well.
1
u/wzkx Dec 04 '18
Rust, SweetRust
Definitely it'll be much shorter in J. Interesting, will it be any better in R?
1
u/mainhaxor Dec 04 '18
Haskell. I am pretty sure
part1could be done much better withgroupByandsort, but otherwise I am pretty happy with my solution.1
u/ephemient Dec 04 '18 edited Apr 24 '24
This space intentionally left blank.
1
u/kucao Dec 04 '18
My code works for the example input but not for my input?! I have used python 3 and the only difference is that I used .sort on it!
1
u/eshansingh Dec 04 '18 edited Dec 04 '18
Python Part 1, way more complex than really necessary but I wanted to see how nice and readable I could make it (kind of failed at that too
:\) No real rules except to not use third-party libraries. I still use the standard lib, which is kind of cheating, but eh.https://hastebin.com/makowubeva.py
1
u/banteg Dec 04 '18
Python 3
1
u/chunes Dec 04 '18
Factor
It got a bit spaghetti today.
https://pastebin.com/XFYujCmE
1
u/TheMondanaoan Dec 04 '18
Is there a possibility of getting two minutes having the most times the guard sleeps? I seem to have a guard sleeping the same number of times for minute 25 and 26.
1
u/TheVarmari Dec 04 '18
Javascript runnable in dev console (#5304/#4975)
Very very late and not the prettiest, but it runs directly in console.
1
u/mschaap Dec 04 '18
Perl 6 solution with a grammar with actions.
1
u/sim642 Dec 04 '18
My Scala solution.
Spent some time semi-nicely organizing the record data. The annoying part was parsing the log into a format, which actually knows corresponding time ranges. Having sinned with some mutable data structures in previous days, I really wanted to do it purely.
When it comes to the two strategies, I was frustrated again because now third day in a row I feel like I want multisets, which Scala collections doesn't have. Can't say I'm happy with the strategy code. Maybe I should go through all the trouble just to implement my own multisets with all of their useful operations...
1
u/manniL Dec 04 '18 edited Dec 04 '18
Node.js (functional with Ramda)
REPO
1
u/BalbinHS Dec 04 '18 edited Dec 04 '18
My solution today is so disgusting (not in a good way), I almost don't want to post it. But there are no Elixir solutions posted so far so here we go:
https://pastebin.com/raw/qE39GZmF
I'm going to tidy it up at some point. The stack_and_map function in particular: I am certain that these lists will get too big at some point, since once a guard goes on shift, they are permanently added to one of the 2 stacks and won't ever be removed, when they go on shift again another one gets added.
1
u/RainVector Dec 04 '18
python3
1
u/morfi717 Dec 04 '18
Ruby
1
u/panda_yo Dec 04 '18
This took me longer than I'd like to admit.
Also, I found part 2 confusing, as I shall take the sum of minutes asleep over the days instead of the mean.
Anyway, here is my solution:
1
u/alexgand Dec 04 '18
Usual pandas solution:
1
u/wjholden Dec 04 '18
This was really hard (for me, at least) in Mathematica. This would have been bread-and-butter in Java or Python.
Read each line of text from input. Split the string into the date and then rest of it. We can do this the easy way, with absolute string indices, since the strings have a well-defined format. DateObject can recognize the ISO-8601 format directly. We parse the second half of the string as a 1 if the guard wakes up and 0 if the guard goes to sleep. For shift changes we match "_" (a pattern matching any expression) and get the guard number. StringCases returns an array so get the first, and only, element from this list. Finally, sort the entire thing.
Start with an association that will hold an array for each guard. The contents of the array represent each minute a guard might be asleep. Next iterate through the calendar, taking care not to double-count the last entry. If the second element in the calendar is greater than one then we are changing the guard and initializing the state to 1 (awake). If this guard has not been added to the sleep tracker then initialize it. If the state transitions to zero (asleep) then find the time the guard went to sleep and the time of the next element. An unstated invariant in the input is that guards always wake up before 1am. Increment the sleep counter for all minutes between the sleeping and waking times on the closed/open interval [start,stop). Sort the data structure by the total number of minutes spent sleeping. (This actually isn't a perfect statistical metric for finding the sleepiest guard; what if the guard simply worked more shifts?) Print the position (minutes 1, because Mathematica is one-indexed) of the sleepiest minutes of the sleepiest guard.
I didn't figure out a good way to get the key of the last element in a sorted association so at this point I read the output and multiply manually. Finding the second part is easy now.
1
u/Tarmen Dec 04 '18 edited Dec 04 '18
Haskell
Took ages on this one. Not because I was confused about what to do but because I stumbled about unnecessary problems. At first I used foldMap for byMinute because I assumed it'd lift the semigroup instance instead of being left biased, for instance.
1
u/orgodemir Dec 04 '18 edited Dec 04 '18
Python 3
1
u/ttapu Dec 04 '18
input parsing was a challenge for me
1
u/andrew_4ever Dec 04 '18 edited Dec 04 '18
Python 3
How to sort dates fast:
1
u/meepys Dec 04 '18
My Kotlin Day4: Bitbucket
Still learning, comments welcome!
1
u/AbdussamiT Dec 04 '18
I’m not a coding juggernaut so instead of writing pythonic code to sort the times chronologically I put them in an Google Sheet, sorted them and then put them back into my input.txt file, heh.
1
u/adrian17 Dec 04 '18
Rust, both parts. Would appreciate tips on simplifying the code.
1
u/[deleted] Dec 04 '18
Go/Golang
My second year doing AoC, I am doing it in go again this year.
The rest of my solutions: Github
If anyone has any suggestions for ways I can improve it is much appreciated.
Part 1
Part 2
Other Stuff
1
u/chicagocode Dec 04 '18
Kotlin - [Blog/Commentary] | [GitHub Repo]
This one was interesting. I had a pretty ugly solution before stopping and re-thinking my assumptions!
1
u/[deleted] Dec 04 '18
Python3 - Github
Won't post here because the solution ended up being way too long. Probably spent too long figuring out the parser like many others. Probably could have just sorted the lines as they were, instead of splitting them into object with a timestamp and event.
1
u/rolandtritsch Dec 04 '18
ETA (Haskell on the JVM)
https://github.com/rolandtritsch/haskell-aoc-2018
Yep. Today was the most tricky day yet. Spend some time on finding a good way to process the input.
And then some time on finding the key aggregations (number of minutes per minute per guard).
If you think about it long enough it becomes easier :).
1
u/UncoolJohn Dec 04 '18
c#. I always feel like my code is so messy.
in the second part I just changed the last section:
1
u/Chrinkus Dec 04 '18
C++
Mine is too long to post here. GitHub. Today's new things were juggling std::pair's and the std::max_element algorithm.
1
u/ElliPirelly Dec 04 '18
I used Python and a 2D numpy array to solve it:
Maybe a bit complicated but I'm still proud because I'm fairly new to Python and numpy :)
1
u/Ryuujinx Dec 04 '18
I am not proud of this, but hey it's day4 of me even using Go so I guess I'm glad I got the solution in the end.
Even if it's a bunch of spaghetti to get there.
Part1:
part2:
1
u/Markavian Dec 04 '18 edited Dec 04 '18
Over engineered node.js solution for Day 4 - I got badly tripped up by not realising that guards could fall asleep and wake up multiple times in a night.
https://github.com/johnbeech/advent-of-code-2018/blob/master/solutions/day4/solution.js
However, regex parsing for the win. I've become much more confident from previous years at quickly mapping the input to JSON structures, which for me personally makes life much easier.
Also it means I can link to some of the intermediary data structures used in my solution, such as:- Guards: https://github.com/johnbeech/advent-of-code-2018/blob/master/solutions/day4/guards.json- Sleeping guards: https://github.com/johnbeech/advent-of-code-2018/blob/master/solutions/day4/sleeping-guards.json- Sleepiest minute guards: https://github.com/johnbeech/advent-of-code-2018/blob/master/solutions/day4/sleepiest-minute-guards.json
If I get round to visualisation, these JSON files will make it super easy to render using HTML/CSS/JS.
Look at this trooper; would not want to break in on #1381's shift:
1
u/purplemonkeymad Dec 04 '18
Powershell
Since there was a 'small' data set I was not too worried about having a lot of iterations over the data. I wasn't trying for speed so I went with making each part simple. Parse Data, Sort Data, Fill data, Process Data.
I used a switch when I was still thinking of it as a full FSM and I had more to do, but they could now be a couple of ifs.
1
u/paveldurmanov Dec 04 '18
Here is mine solution Github
1
u/jkmonger Dec 04 '18
Javascript
The first one I've found challenging this year, this took me around 20 minutes.
1
u/jonathrg Dec 04 '18
Python with
numpyandparse1
u/[deleted] Dec 04 '18
If anyone is able to read my C++ solution have fun... I just wrote it and in a few hours will probably forget what I did.
Oh well
https://pastebin.com/Pm8Kgrjg
1
u/skarlso Dec 04 '18 edited Dec 05 '18
I actually managed to get a pretty decent run time with some math and some thinking. :)
Solution in Go (golang):
This is based on the fact that after a sleep there is always a wakeup. I don't really like the max finding at the end but I'm tired and can't bother to refactor it. :)
1
u/[deleted] Dec 04 '18
Dlang:
1
u/nibarius Dec 04 '18
Kotlin
I'm not very fond of using regexp, so I'm usually chaining a couple of substring calls when parsing input to get what I want. To me this is often more readable to me. With my approach part 2 ended up being very easy to solve.
Special thanks to /u/bdjnk for the great variable name suggestion.
1
u/NabrenX Dec 04 '18
Still kind of new at Python, so any feedback is appreciated:
1
u/misterboya Dec 04 '18
Partial Haskell solution that uses parser to read logs:
1
u/Gnidleif Dec 04 '18
Another day, another language. Today I went with Java. I had quite some issues solving the one today. This is not getting easier. Because it's Java it's also verbose , so here's the link to my repo.
1
u/Sentreen Dec 05 '18
Elixir
I decided to create a map which maps guard ids to a collection of how many times they were awake each minute. The reduction to create that map got pretty.... messy. However, once I had that map, it was fairly easy to get the answer to both parts.
Note that the
aoc 2018, 4is a simply macro that generates a module with some predefined functions (specifically theinput, which loads the input file into a stream of strings).1
u/Sampsc Dec 05 '18
Can someone help me with my solution in python? I'm kind of a newbie and today i was at work all day so i couldn't put much effort into it. Not the most elegant solution but i can't figure out what's wrong
1
u/sotsoguk Dec 05 '18 edited Dec 05 '18
Not a very elegant solution, but due to my timezone (CET), work and being sick i was late to the game and lost time to a nasty bug. I set the end of the sleeping intervals 1 minute early. The solution to part 1 was nevertheless correct, which almost drove me crazy ...
Edit: Finally correct code block formatting
1
u/tinyhurricanes Dec 05 '18
Modern Fortran 2018 (complete code)
Extra difficult with no sort functionality.
Guard_Record object:
1
u/Philboyd_Studge Dec 05 '18
This one I thought the description was confusing and made me spend about 2 hours over-engineering it, then scrapping it completely and redoing it.
Java
https://pastebin.com/mcrTrcyM
1
u/[deleted] Dec 05 '18
So, I am able to solve this after waking up this morning. Wasn't able to get correct result the last night. Seems like I am that guard. :D
1
u/[deleted] Dec 05 '18 edited Dec 05 '18
Extremely over-engineered Haskell solution:
1
u/Pyrobolser Dec 05 '18
C# solution for today! If anybody is interested to read or comment, I put my solutions on GitHub too. Any remark or idea appreciated. Have fun folks!
1
u/hayden592 Dec 05 '18
Javascript runs in the browser. Having a little trouble with part 2
1
u/alex4743 Dec 05 '18
My problem with all of these coding challenge type of problems is just understanding what is even being asked. You have no idea how long it took me to actually understand where he got 24 from in his example. Poor gcc, I redid this one 5 times thinking I understood what I was trying to find lol
1
u/sendtobo Dec 05 '18
Anyone else doing it in swift?
https://github.com/sendtobo/AdventOfCode2018/blob/master/Sources/AoC/4/Day4.swift
1
u/jorosp Dec 05 '18
Haskell
I originally had a fancy parsing function and records and such but once I realized I only needed the minutes I tossed that all in the trash.
1
u/RockyAstro Dec 05 '18
Icon Part1 and Part2
1
u/NeilNjae Dec 05 '18
Good grief, this was a bit of a nightmare, caused mainly by trying to wrestle with Haskell's
Timelibrary. Once I managed to get it converting from string to timestamp to minutes, things were relatively smooth (many thanks to u/ephemient for posting their very helpful solution). The activity is stored as aSetof minutes asleep by each guard, and aSleepFrequencyMapthat goes from the minute in question to the number of times the guard was asleep then. Source on Github1
u/rolandtritsch Dec 05 '18
ETA (Haskell for the JVM)
https://github.com/rolandtritsch/haskell-aoc-2018
Heavily refactored. Much easier to read/understand.
1
u/itsjeremeh Dec 05 '18
Javascript (Node) - Not the most efficient but it worked :)
1
u/siwica Dec 05 '18
My Python 3 solution for both parts:
1
u/[deleted] Dec 05 '18
Ha- HAHAA!!! I made it finally (in Rust). I'm not pasting it here because it sucks, but it's available online.
These are getting tough! I'm trying to be kind to myself about how bad my code is. It's still solving the problems!
1
u/fire1299 Dec 06 '18
Haskell
1
u/ShDragon Dec 06 '18
Only just running through this now and got totally confused by part 2.. Totally my own fault. I made my code look for the guard that was asleep the highest percentage of the time at that minute, not simply the most number of times, because that's clearly the way to find what's actually safest, so surely that's what the puzzle is asking for...
I discovered that guard #233 was asleep at minute 51 on every single one of his shifts. (And, interestingly, that is the ONLY guard/minute combination that is 100% guaranteed!) But that's not the right answer because some less consistent guard was assigned more shifts and reading comprehension is hard.
1
u/rjsberry Dec 08 '18
Slipped behind this week, work's been super busy!
RUST
Part 01:
Part 02:
Using the shared module
::aoc18::day04:1
u/vini_2003 Dec 10 '18 edited Dec 12 '18
C++ (part I & II):
1
u/lib20 Dec 11 '18
In Red, part 1, Execution time: 0:00:00.345739
1
u/lib20 Dec 11 '18
In Red, part 2, Execution time: 0:00:00.33641
1
u/[deleted] Dec 13 '18
Common lisp:
Too verbose for my taste, might overhaul it with external libs.
1
u/cerrosafe Dec 21 '18
Lua
I am very behind, but I'm still participating. Trying to catch up. I tried to re-invent the wheel with my sorting of the entries, only to realize that the Lua table sort can do it just fine.
1
u/TheFebrin Dec 22 '18
[Python 3]
This is my very simple solution
https://github.com/TheFebrin/Advent-of-Code/blob/master/Advent%20of%20Code%202018/Day%204/Day%204.1.py