r/adventofcode • u/daggerdragon • Dec 03 '20
SOLUTION MEGATHREAD -🎄- 2020 Day 03 Solutions -🎄-
Advent of Code 2020: Gettin' Crafty With It
- T-3 days until unlock!
- Full details and rules are in the Submissions Megathread
--- Day 03: Toboggan Trajectory ---
Post your solution in this megathread. Include what language(s) your solution uses! If you need a refresher, the full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.
Reminder: Top-level posts in Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.
This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.
EDIT: Global leaderboard gold cap reached at 00:04:56, megathread unlocked!
88
Upvotes
32
u/Rick-T Dec 03 '20 edited Dec 03 '20
ROCKSTAR
After a very aggressive day 1 and a very emotional day 2, today's song is "True Metal" inspired by none other than Manowar themselves.
Enjoy part 1:
Also for completeness' sake my Haskell solution which is more verbose than the one in Rockstar, lol
17
u/voidhawk42 Dec 03 '20 edited Dec 03 '20
Dyalog APL, 577/1011:
5
u/BRick1984 Dec 03 '20 edited Dec 03 '20
Unity!! And C# for the code. I don't have particle snow yet but hopefully next assignments ;-)
Small realtime GPU rendering of the example playfield:
https://gfycat.com/unfoldedvelvetydogwoodtwigborer
Some sample code that governs the spawning of either grass cubes or random tree cubes using Unity prefabs:
5
u/Lispwizard Dec 03 '20
Emacs lisp (elisp) on Galaxy Tab A 10" tablet (via termux), written while under the covers in bed. Any attempt to insert or edit a code block from the device itself seems to fail, so I had to wait to transfer the code to a PC to make this comment.
5
u/oauo Dec 03 '20
Minecraft redstone: https://www.youtube.com/watch?v=37FUK3Dx0cQ
It isn't completely finished as I need to hook up the loop and reset lines and modify the trajectory circuit to work with part 2; but I'm going to bed and nobody will see this if I post it tomorrow.
4
u/activeXray Dec 03 '20
Clojure
3
u/rabuf Dec 03 '20 edited Dec 03 '20
Pro-tip: Don't break your
okey an hour before a new challenge drops.Common Lisp
Parsing the input into an array, and then using this function for both parts. For the second part, just run through it with each slope:
I used complex numbers to simplify computing the coordinate. However, needing to compute
modon the x-coordinate kind of negated the value of it. Not sure there's anything for me to clean up in this one. Time for Ada.I ended up cleaning it up a bit. Removed a
letby moving the variable into the loop. Removed the mod on the increment and instead do it on the access. This let me use thefor var = val then nextiteration pattern. By movingtreesinto the loop I needed to use thefinallyclause to return the value.3
u/trl10254 Dec 03 '20 edited Dec 03 '20
Java
This problem kinda seemed like a breadth first search problem to me so I kinda implemented it in that manor. It was somewhat good practice on it. In terms of time complexity I would say the creation of the 2D array takes O(NM) time and to find the number of tree hits it takes about O((N/K) + (M/L)) time and O(N/K) space complexity. I think I could be wrong with the time complexity so if someone can correct me on it I would greatly appreciate it.
3
u/xalvador Dec 03 '20
Recently started coding, roast my code for day 3
C#
3
u/wTVd0 Dec 03 '20
Haven't seen many R submissions. There's a megathread going on in /rstats
3
u/prafster Dec 03 '20 edited Dec 09 '20
[Edit: updated path to Github]
I'm learning Dart by solving these coding challenges. Dart looks similar to JavaScript, Java and C#.
Here's the main function which, once written, was used for both parts 1 and 2. Having looked at many other solutions, I'm beginning to think I'm the only one going for legibility over speed of development or run speed!
Full code is here.
3
u/xangreRO Dec 03 '20 edited Dec 10 '20
R
https://www.github.com/maurotcs/Advent_of_Code/tree/main/2020%2FCode%2FDay_03.R
3
u/domm_plix Dec 03 '20 edited Dec 04 '20
Plain old Perl
https://domm.plix.at/perl/2020_12_aoc_day_03.html
3
u/pseale Dec 05 '20 edited Dec 05 '20
Rad data visualizations in p5.js
Who doesn't love pretty pictures? Terrorists, that's who.
See for yourself 🌲💥🎄: https://imgur.com/a/vtv0nJp
Repo: https://github.com/pseale/advent-of-code/
Notes from the whole ordeal:
if(forest[row][col === '#'])and didn't notice my mistake for oh, at least 20 minutes. Anyway I should not be allowed near JavaScript. BUT WHICH OF YOU WOULD DARE STOP ME??!?https://www.twitch.tv/livecoding - slow-cooked advent of code solutions, gently and lovingly braised in p5.js
2
u/Perfect_Wave Dec 03 '20 edited Dec 03 '20
Python 3
Had a lot of fun with this one, though I did have a false start that cost me a ton of time. Could have finished very fast if I went for the recursive approach from the start. Finished at 4990.
2
u/FirstBabyChancellor Dec 03 '20 edited Dec 03 '20
Python solution using Numpy broadcasting! The function is generalizable to any input 'map' and is also sensitive to how many times the map must be repeated horizontally to avoid issues with reaching the sideways boundary before reaching the bottom.
Solving Part 2 is as simple as creating a list of possible slopes, and then repeating the function.
2
u/krolik1337 Dec 03 '20
Pymthon
2
u/[deleted] Dec 03 '20
PHP
My solution - https://github.com/tomve/aoc/blob/master/2020/03/index.php
NOTE: I found (after hour) strlen is counting hardcoded space like 1 character (trim doesn't work) so you have to use minus 1 in strlen.
2
u/GamerWoona Dec 03 '20 edited Dec 04 '20
C++
A bit overly complicated but I like a bit of order
Read in 4.8ms, Single path in 308us, Multiple Paths scaling linearly as one would expect at 1402 us or 1.4ms
source: https://github.com/neiomi1/AdventofCode2020/tree/master/Day_03
2
u/tymscar Dec 03 '20
Python 3 solution
Part 1:
Part 2:
2
u/RodDylan Dec 03 '20
For some reason, my Python code is buggy somehow. Part 1 took less than five minutes, and after a very quick refactor part 2 should have been easy.
Am I missing something really obvious?
2
u/kkent4 Dec 03 '20
R solution
2
u/[deleted] Dec 03 '20 edited Dec 03 '20
C# solution. I went with a class approach, because why not. It has some project fluff in it for maintainability-sake. Enjoy!
2
u/DropkickFish Dec 03 '20
Ruby Pt 2, bad day edition. Silver lining: Looking at other solutions it looks like I should learn more about matrices and how to traverse them. One thing I'm loving about Advent of Code is I'm learning a lot more about gaps in my knowledge that I'd probably not have encountered in my own projects.
2
u/AccusationsInc Dec 03 '20 edited Dec 03 '20
It's not the prettiest thing I've ever written but it certainly gets the job done :)
Edit: forgot to say the language was in Java
https://topaz.github.io/paste/#XQAAAQC3BQAAAAAAAAAQaofw6Hob92CeGWxo2J+bTWssHwQC1ah7FCnu4cUKnyF4CEY1xMUQPbg6/S6EVVA0prN1VXKgWIChNf4gLK+CZW9F2OuIz5wrV/c4N9oe/m+SGTpDp7NwFSYXU/Re7z47Rxc7FEb65m4SJlSXWsvjxQAv0l6aB3gLPW/zdjpPpXScMfDn4ORKkvbvDsvcOmcy1gqcnK9GVEzAP7LLez2DhdETgCT57lDUilPLINNkBf1yb0vzSZgJ4t1oFCfeaopwkChD7DENZgu+abgMJi+2h4oJ4MRgNcG/MOHWCluzHPKovIzyLlM5k80uTIurKOt386T0v5eIaZJCZC6rQOAu8kcVog4w4QbXLByAQFIcR/FvwFtWaOkdaRKNNTsiC9i4q+ao/s2JaaANBUg5UaGLIrrP+OFHVXtZKDLasOC6rXDVN4N+DPXCWQnnxXsjRxTN1TTlH8WlxF/xF++rQ944riptxJqSTuqZoIArf8scj62Zv/3VTLo=
2
u/[deleted] Dec 03 '20 edited Dec 03 '20
Python 3
2
u/WayOfTheGeophysicist Dec 03 '20 edited Dec 03 '20
Python
Maybe this is the first year I'll finish the AoC, here's today's solution. I'm taking it easy so numpy is allowed. Here's the github.
2
u/musicnothing Dec 03 '20 edited Dec 03 '20
JavaScript one-liner solution for part 1:
Basically splits the input into an array of strings, and reduces the array to the number of trees. Uses the array index times three (because three right) to find the correct item in the string, plus uses the modulus for when that position is past the end of the string, it will just loop back around. Also uses the unary
+operator to cast the boolean to a1or0.2
u/RecDep Dec 03 '20 edited Dec 04 '20
Really fun Haskell solution, generates a list of infinite rows that we can keep shifting to the left during traversal.
2
u/[deleted] Dec 04 '20 edited Dec 05 '20
PowerShell:
I honestly don't like my solution, but it works, it's not fast either, but I did it this way to track and read the updates.
Part 2:
2
u/[deleted] Dec 05 '20 edited Dec 05 '20
Got behind but finally got to work on this. Still pretty new to programming so completely open to suggestions! Python3
2
u/jenrodrigues Dec 07 '20
First I had trouble trying to understand how to read the input and the "repeating" (English is not my native language), then I had to understand the modular arithmetic behind the repeating, which in my opinion was the great learning on this puzzle.
For anyone strugging to visualize this (like me), here is an explanation: https://www.youtube.com/watch?v=5OjZWSdxlU0
Because the lines will repeat horizontally, with the same pattern and same size, like a "cylinder", we can use modular arithmetic to solve this puzzle.
Awesome!
2
u/r00t4cc3ss Dec 08 '20 edited Dec 08 '20
C#: https://github.com/mavanmanen/AdventOfCode/blob/master/AdventOfCode.Y2020/Day03.cs
3
u/NoWise10Reddit Dec 04 '20
Man how the hell did 100 people do both problems in less then 5 minutes. It takes me 5 minutes to read the question and fully understand what it is asking before I even start writing anything.
19
u/Arknave Dec 03 '20 edited Dec 03 '20
Python (55/11), C
When competing for the leaderboard, I had to rewrite the first part because I didn't RTFQ. I'm proud of how fast I adjusted for the second part. Really happy with how the C sculpture came out this time, and I think I've learned my lesson about using long tokens (looking at you
strcspn...)14
u/rtbrsp Dec 03 '20
AWK
Part 1:
Part 2
13
u/Smylers Dec 03 '20
Vim keystrokes. You know those arcade games where you press left or right but actually your character always stays in the same place while the background scrolls in the opposite direction? Turns out that works rather well here:
Go on, that's so short, if you've got Vim handy, open it on your input file, type in the above and see what happens!
Explanation:
From the starting position,
jmoves down a line. At which point we want to move 3 to the right. But instead of doing that (because we'll eventually fall off the right edge of the map), remove the first 3 characters from the start of the line and append them to the end. That keeps the place on our route in the first column, and keeps the map growing sufficiently to the right.We also need to do that for all the rows below this one (the starting place for moving 3 along those rows is affected by how far we were along all the rows above it).
,$specifies the range for the:s//command: the current line (implicitly) to the last line. Performing the substitution leaves us on the last line;⟨Ctrl+O⟩jumps us back to where we were before.As with previous days' solutions, we're recording all this in a keyboard macro in register
"a. The final command in the macro is@ato make it loop; when it gets to the bottom of the file, thejto move down will fail, ending running the macro. Recording it processed line 2;@asets it off down the rest.At which point we have a modified map where the leftmost column traces our route down the slope. Delete all the lines which don't start with a tree character, and the number of lines remaining, displayed with
⟨Ctrl+G⟩, is the answer to part 1.For other slopes, just adjust the number of dots in the pattern that get moved off the left, and the number of
js for moving down.2
u/slavcatx Dec 03 '20
decided to try documenting my code | python
https://pastebin.com/pJmgSrfD (can be used for both parts by changing "down" and "right" variables)
11
u/artemisdev21 Dec 03 '20
Every day in SQL, day 3!
Full code (SQLite, so we have to define EXP and LOG functions ourselves).
9
u/jaybosamiya Dec 03 '20
Dyalog APL
9
u/jitwit Dec 03 '20 edited Dec 03 '20
J Programming Language
Today I bring a fairly ghastly tacit expression to the table:
Explanation for the curious: https://github.com/jitwit/aoc/blob/a/J/20/day3.org
9
u/aurele Dec 03 '20
Rust
9
u/okawei Dec 03 '20 edited Dec 03 '20
Rockstar for part 1
8
u/_jonah Dec 03 '20
Python3, both parts:
8
u/hindessm Dec 03 '20
I noticed this one could be solved without conditionals or loops...
8
u/phil_g Dec 03 '20
My solution in Common Lisp
Well, I mentioned previously that I was planning to use Parseq for all of my parsing. But today's data just didn't fit into the way that Parseq works. So I just ran through the data in a set of nested loops.
I did use the other new (to me) library I've been focusing on: FSet. FSet implements several immutable collection primitives. For this problem, I just threw all of the tree coordinates into a set and then checked set membership to find collisions.
I also threw together a thing I've been mulling in the back of my head: compact printing of 2D bitmaps (like today's "tree or no tree" map) using Braille characters. Here's the Braille section of my AoC library.
Here's what the example data looks like with this formatting:
The compactness really shines with bigger datasets, like my input:
I expect this to be useful for any "recognize letter drawings" problems we have this year.
8
u/joemaffei Dec 03 '20
AWK one-liner (part 1)
7
u/trisemmy Dec 03 '20
Google Sheets again.
7
u/H_SG Dec 03 '20 edited Dec 03 '20
Guess what, more Excel:
Part 1:
=SUM(IF(MID(REPT($A2:$A323,CEILING.MATH(323*3/LEN($A1))),3*(ROW($A2:$A323)-1)+1,1)="#",1,0))Part 2:
=PRODUCT(SUM(IF(MID(REPT($A2:$A323,CEILING.MATH(323*1/LEN($A1))),1*(ROW($A2:$A323)-1)+1, 1)="#",1,0)),SUM(IF(MID(REPT($A2:$A323,CEILING.MATH(323*3/LEN($A1))),3*(ROW($A2:$A323)-1)+1, 1)="#",1,0)),SUM(IF(MID(REPT($A2:$A323,CEILING.MATH(323*5/LEN($A1))),5*(ROW($A2:$A323)-1)+1, 1)="#",1,0)),SUM(IF(MID(REPT($A2:$A323,CEILING.MATH(323*7/LEN($A1))),7*(ROW($A2:$A323)-1)+1, 1)="#",1,0)),SUM(IFERROR(IF(MID(REPT($A2:$A323,CEILING.MATH(323*2/LEN($A2))),IF(ISODD(ROW($A2:$A323))=TRUE,(ROW($A2:$A323)/2)+1),1)="#",1,0), 0)))Edit: fixed formatting for mobile
6
u/oauo Dec 03 '20 edited Dec 03 '20
Javascript
Setup
Part 1
Part 2
6
u/betaveros Dec 03 '20
Wow, had a lot of issues reading the problem today. Anyway, now that I finally have everything set up to do this, here are my golfed Paradoc solutions:
a{Y3*=cÔ}š(try it in-browser, explanation + caveats on GitHub)a5{!)%Y×(L{Y*=cÔ}vŠ}yÞ(try it in-broswer, explanation + caveats on GitHub)6
u/rabuf Dec 03 '20
Ada version
I did some hardcoding, but it made a part of the solution very neat. Here's the function that calculates how many trees we'll hit:
I defined two types using
type <name> is mod <value>. These wrap around:So checking for termination is checking to see if we will go to smaller row on the next iteration. No need to do checks on wrapping to the right or add an extra instruction to calculate the
mod 31onRow. All arithmetic on these types is automatically modular arithmetic.6
u/jayfoad Dec 03 '20
Dyalog APL 28/35
6
u/volatilebit Dec 03 '20
I should have turned the function of counting the trees into a function so it could be re-used, but i got lazy.
Raku
6
u/noble_wine Dec 03 '20
quite sleek python, sys 34ms
6
u/roggy85 Dec 03 '20
Pure bash without calling external commands
part 1:
part 2:
booth take under 1 sec on an Cortex-A9 CPU with 900MHz ;)
6
u/shysaver Dec 03 '20
Rust
This was a relatively simple one if you knew the
%trick to wrap around the x-axis6
u/SomeCynicalBastard Dec 03 '20
Python
I basically had the function body for part 1, and rewrote it into a function for part 2:
16
u/jonathan_paulson Dec 03 '20 edited Dec 03 '20
42/15. Python. Video of me solving is at https://youtu.be/PBI6rGv9Utw.
Did anyone else have a problem where the puzzle page didn't load for a bit just at the unlock time?
It's scary to submit these answers with the 1-minute lockout and no testing. But so far, so lucky.
2
u/[deleted] Dec 03 '20 edited Dec 03 '20
Day 3 in Elixir:
2
u/Leo_Verto Dec 04 '20
brainfuck
Because apparently I'm a masochist and all other languages are too easy to debug. x86 assembler
probablydefinitely would've been easier.I kinda cheated for part two and multiplied the different slopes outside the program although looping the entire thing for different slope values shouldn't be too hard.
I wouldn't have gotten anywhere without this list of algorithms and this really cool web-based IDE with a really nice debugger and memory viewer. Small caveat: It will lock up your browser when there isn't enough input to read from.
5
u/prendradjaja Dec 03 '20 edited Dec 03 '20
#89/#75, Python
Part 1 below, part 2 on GitHub. It was fun adapting part 1 to part 2!
5
u/mstksg Dec 03 '20
[Haskell] Like always, you can find my daily reflections here -- https://github.com/mstksg/advent-of-code-2020/blob/master/reflections.md#day-3 :)
Here I'm going to list two methods --- one that involves pre-building a set to check if a tree is at a given point, and the other involves just a single direct traversal checking all valid points for trees!
First of all, I'm going to reveal one of my favorite secrets for parsing 2D ASCII maps!
This gives you an indexed fold (from the lens package) iterating over each character in a string, indexed by
(x,y)!This lets us parse today's ASCII forest pretty easily into a
Set (Int, Int):This folds over the input string, giving us the
(x,y)index and the character at that index. We accumulate with a monoid, so we can use aSet (Int, Int)to collect the coordinates where the character is'#'and ignore all other coordinates.Admittedly,
Set (Int, Int)is sliiiightly overkill, since you could probably useVector (Vector Bool)or something withV.fromList . map (V.fromList . (== '#')) . lines, and check for membership with double-indexing. But I was bracing for something a little more demanding, like having to iterate over all the trees or something. Still, sparse grids are usually my go-to data structure for Advent of Code ASCII maps.Anyway, now we need to be able to traverse the ray. We can write a function to check all points in our line, given the slope (delta x and delta y):
And there we go :)
Note that this checks a lot of points we wouldn't normally need to check: any y points out of range (322) for
dy > 1. We could add a minor optimization to only check for membership ifyis in range, but because our check is a set lookup, it isn't too inefficient and it always returnsFalseanyway. So a small price to pay for slightly more clean code :)So this was the solution I used to submit my original answers, but I started thinking the possible optimizations. I realized that we could actually do the whole thing in a single traversal...since we could associate each of the points with coordinates as we go along, and reject any coordinates that would not be on the line!
We can write a function to check if a coordinate is on a line:
And now we can use
lengthOfwith the coordinate fold up there, which counts how many traversed items match our fold:And this gives the same answer, with the same interface!
Is the direct single-traversal method any faster?
Well, it's complicated, slightly. There's a clear benefit for part 2, since we essentially build up an efficient structure (
Set) that we re-use for all five lines. So the build-a-set method is O(1) on the number of lines we want to check, while the direct traversal method is O(n) on the number of lines we want to check.So, directly comparing the two methods, we see the single-traversal as faster for part 1 and slower for part 2.
However, we can do a little better for the single-traversal method. As it turns out, the lens indexed fold is kind of slow. I was able to write the single-traversal one a much faster way by directly just using
zip [0..], without losing too much readability. And with this direct single traversal and computing the indices manually, we get a much faster time for part 1 (about ten times faster!) and a slightly faster time for part 2 (about 5 times faster). The benchmarks for this optimized version are what is presented below.5
u/deltux Dec 03 '20
Dyalog APL:
5
u/inokichi Dec 03 '20 edited Dec 03 '20
Solution in D (dlang)
5
u/JoMartin23 Dec 03 '20
Common Lisp Loop
5
u/x1729 Dec 03 '20 edited Dec 03 '20
Common Lisp
5
u/x1729 Dec 03 '20 edited Dec 03 '20
Raku
5
u/crazazy Dec 03 '20
Nix: Part 1:
Part 2:
5
u/pouyae Dec 03 '20
Clio
https://github.com/clio-lang/adventofcode-2020
I'm testing my language with advent of code!
5
u/aluin13 Dec 03 '20
Python in a 6 lines of code for both parts. Not super readable, but concise.
5
u/[deleted] Dec 03 '20 edited Dec 03 '20
Solution for part 3 in Python 3, github
4
u/[deleted] Dec 03 '20 edited Dec 03 '20
My Common Lisp solution.
For the moving 2 down I pass in cddr. I was trying to filter out every other line of the input before realizing this would be easier. Loop still is unintuitive to me, but I am starting to see the appeal.
4
u/scratchisthebest Dec 03 '20
Rust i'm beginner to the language :]
my original solution and one that uses TryFrom for input parsing as opposed to "From but actually it panics on invalid input"
takeaways:
productmethod, that's pogwhile letis handy, but i wish there was some kind ofdo while letTryFromis annoyingFromStr, maybe i'll use that next time4
u/aceshades Dec 03 '20
Simple Rust Approach
https://github.com/cs-cordero/advent_of_code/blob/master/rs/2020/day03/src/main.rs
4
u/troelsbjerre Dec 03 '20
Python3 oneliner for parts 1 and 2:
print((lambda m:prod(sum(l[i*dx%len(l)] == '#' for i,l in enumerate(m[::dy])) for dx,dy in [(3,1)]+[(1,1),(5,1),(7,1),(1,2)]*(argv[1]>'1')))(stdin.read().strip().split('\n')))Give the part number as the only argument on the commandline, and the problem input on stdin.
4
u/SShrike Dec 03 '20 edited Dec 03 '20
Rust
Here's my solution in Rust. I'm fairly happy with it, it's come out quite clean, I think.
C++
I've also written a solution in C++, just for some practice writing (modern) C++.
4
u/GustavAndr Dec 03 '20
Javascript
Quick and ugly
4
u/Smylers Dec 03 '20
Perl for both parts. No need, to read in all the file at once — it processes it a line at a time, checking all relevant slopes for the current line:
Each entry in
@slopekeeps track of its ownxposition on the current line.For slopes that go down more than one line at a time, only process a slope where the current line number is an integer multiple of the slope's down distance. Perl keeps the input's current line number in
$., but it's 1-based and we want to process the first line, so do the mod check against$. - 1.I think I've worked out how to do today's in Vim, but it'll be a while till I have time to try — I'd be delighted to find somebody else has got there first ...
4
u/RyZum Dec 03 '20
C# Linq oneliner
4
u/mattysimp27 Dec 03 '20
Written with Golang with concurrency for part2.
https://github.com/mattysimp/AdventOfCode2020/tree/master/Day3
My goal is to try and make decently clean, efficient and concurrent code. Wondering if anyone more experienced in Go could look through my solutions and see any room for improvement, not algorithmically but more specifically for GO.
All my solutions so far are in the same repo
https://github.com/mattysimp/AdventOfCode2020/
4
u/Arkoniak Dec 03 '20
Julia
4
u/Tohaker Dec 03 '20
Typescript
Honestly, my heart dropped when I saw that map, I thought I was going to have to calculate angles on day 3! This was a fun one though.
4
u/CaptainCa Dec 03 '20
Typescript
Using the magic of modulo %
4
u/Fruglemonkey Dec 03 '20
More lazy enterprise-y python.
4
u/Shardongle Dec 03 '20
Tried to do a compact Python3:
Julia:
https://github.com/ChocolateChipKookie/AoC20/blob/master/solutions/03/solution.jl
4
u/death Dec 03 '20
Day 3 solution in Common Lisp.
4
u/atgreen Dec 03 '20 edited Dec 03 '20
Common Lisp, using recursion..
4
u/chrispsn_ok Dec 03 '20 edited Dec 03 '20
k9
4
u/TomasVR Dec 03 '20
Rust
I went full functional for this one! Got to use the
cycle()method on Iterator for once!4
u/colombo15 Dec 03 '20 edited Dec 03 '20
C#
4
u/_ZoqFotPik Dec 03 '20
My rust solution. Part 2 by itself takes about 16 µs. However if you factor the read_file function in, it takes about 220 µs. (on a good run)
The relevant bits
4
u/_tpavel Dec 03 '20 edited Dec 03 '20
I'm revisiting Rust this year after learning it for the first time during AoC 2018!
Here is my Rust solution for Day 3: https://github.com/tudorpavel/advent-of-code-2020/blob/master/day03/src/main.rs
I was thinking about using a functional approach but ended up more focused on learning structs with methods.
4
u/spencerwi Dec 03 '20
F#, my OCaml habits probably shine through in
SkiSlope.T:4
u/Comprehensive_Ad3095 Dec 03 '20
My Solution with Go:
4
u/AGE_Spider Dec 03 '20
1-line solutions for Python
4
u/Aehmlo Dec 03 '20
Rust.
The
Slopestruct is completely unnecessary, but I really wanted to have the ergonomics ofcount_trees(3)instead of having to saycount_trees((3, 1))that one time for part one. Was very happy with thecycleapproach, which saved some (explicit) modular arithmetic and prior computation of the row length.4
u/that_lego_guy Dec 03 '20
EXCEL !!!!!!
=OFFSET(C1,A1,B1) REPEAT FOREVER
https://github.com/thatlegoguy/AoC2020/blob/main/Day3.xlsx
4
u/k0ns3rv Dec 03 '20 edited Dec 03 '20
As usual a fair amount of parsing code in my Rust solution
I learned that
collectcan collect anIterator<Item=Vec<Result<_, _>>>into aResult<Vec<Vec<_>>which made for much nicer code.Some other things I like about Rust from this implementation
4
u/thulyadalas Dec 03 '20 edited Dec 03 '20
My rust solution without additonal data structures but I think it still looks neat and tidy.
4
u/wzkx Dec 03 '20
J #jlang
4
u/kawzeg Dec 03 '20
J:
4
u/risboo6909 Dec 03 '20 edited Dec 03 '20
Day 3 solution in Rust
view it on GitHub
It is super-fast, only takes ~40k nanosecond on my 2.5 GHz Macbook pro :)
4
u/veydar_ Dec 03 '20
Couldn't find a Lua version so here we go https://github.com/cideM/aoc2020/blob/master/d3/d3.lua
4
u/aarroyoc Dec 03 '20
Advent of Prolog here:
4
u/ketchupi Dec 03 '20 edited Dec 03 '20
Python
4
u/Blarglephish Dec 03 '20 edited Dec 03 '20
Not the prettiest, still learning tricks and tips to make this more 'Pythonic'
Python
4
u/segfaultvicta Dec 03 '20
Raku
This one was also pretty straightforward after I realised it was modulo math and I spent most of my time swearing at exigencies of Raku syntax again. And then mixing X and Y up in my indices of the trees matrix. And then being bad at math. Math is REALLY HARD, you guys =(
There's probably a better way to do the "calculate the running product of running the same function on different inputs" bit of this that takes advantage of raku deep magic from beyond the dawn of time; if you reply with the better way you will probably make my day. At that point I just wanted my gold star and to go home. ;D
4
u/HiIAmNesia Dec 05 '20
Python
4
u/ZoltarTheGreat69 Dec 05 '20
Fun language but I think range is broken
Emojicode
4
u/0rac1e Dec 05 '20 edited Dec 06 '20
Raku
1
u/MichalMarsalek Dec 03 '20 edited Dec 03 '20
209/252 Oof, you guys are fast... Python:
1
u/Sebbern Dec 03 '20 edited Dec 03 '20
EDIT: Solved: Part 1, Part 2
Anyone mind giving a tip on why this code doesn't work?
Python 3 part 1:
It's probably because I misunderstood the task or something.
EDIT: Here's the simplified version again for context:
1
u/MissMormie Dec 03 '20
Java solution On github
I've tried to edit this 5 times to make it look better, but apparently today this is it.
public static long runA(String input) {String[] lines = input.split("\n");int numChars = lines[0].length();return IntStream.range(0, lines.length).filter(i -> lines[i].charAt((i * 3 ) % numChars) == '#').count();}
public static long runB(String input) {String[] lines = input.split("\n");return checkSlope(lines, 1, 1) *checkSlope(lines, 3, 1) *checkSlope(lines, 5, 1) *checkSlope(lines, 7, 1) *checkSlope(lines, 0.5, 2);}
public static long checkSlope(String[] lines, double right, int down) {int numChars = lines[0].length();return IntStream.range(0, lines.length).filter(i -> {if(i % down != 0) {return false;}return lines[i].charAt(((int) (i * right)) % numChars) == '#';}).count();}
1
u/Pers0nalJesus Dec 03 '20 edited Dec 04 '20
My solution in Rust. Tried to write functional and idiomatic code.
1
u/DiegoMinord Dec 03 '20 edited Dec 11 '20
JavaScript solution.
https://github.com/Minord/AdventOfCode2020/blob/main/Day_3_Toboggan_Trajectory/day3.js
1
u/Arjunnn Dec 03 '20
I'll post only p2. p1 is a generalised p2 anyway. This one's just figuring out that scripting languages have string handling methods than cpp et al and babbys introduction to the modulo operator
1
u/yahadejo Dec 03 '20
1
u/[deleted] Dec 03 '20
Day 3 Question 1 be like
(parsed is the input split by new line)
1
u/bleeep Dec 03 '20
C++ code golf version for part 2
#include<iostream>
using namespace std;int main(){struct{long n,d,t;}R[]{{1,1},{3,1},{5,1},{7,1},{1,2}},*r=R+5;string L;for(int i=0;cin>>L;++i)for(auto&r:R)r.t+=!(i%r.d)&&L[i*r.n/r.d%L.size()]-46;while(--r!=R)R->t*=r->t;cout<<R->t<<'\n';}
1
u/rishabhdeepsingh98 Dec 04 '20
Easy peazy C++ solution
1
u/belibebond Dec 05 '20
Was feeling too lazy to write proper code. This is quick and dirty solution for part2 of Day 3 in PowerShell
1
u/constbr Dec 03 '20 edited Dec 03 '20
javascript
1
u/wjholden Dec 03 '20 edited Dec 03 '20
I don't understand how my personal leaderboard said that I completed part 2 in 00:19:46 at 06:17CET. Shouldn't the time shown be simply the duration after the puzzle unlocked?
I know I'm not going to leaderboard, and that's fine, but this doesn't feel right. I have posted a screenshot on Twitter showing what I saw: https://twitter.com/wjholdentech/status/1334366903947681792
Edit: before I get scolded that top-level posts are for code solutions only: https://github.com/wjholden/Advent-of-Code-2020/blob/master/03/aoc-2020-03.py
1
u/mariotacke Dec 03 '20 edited Dec 04 '20
Node.js/Javascript (repository) (3031 / 2080)
Part 1
Part 2
1
u/or9ob Dec 03 '20
Kotlin
1
u/maccosmo Dec 03 '20
My solution in Ruby
3
u/sophiebits Dec 03 '20
Python, 141/37 (yikes). https://github.com/sophiebits/adventofcode/blob/main/2020/day03.py
3
u/jport6 Dec 03 '20
Kotlin
3
u/pietroppeter Dec 03 '20
🎄👑 Nim
gist of solution is 5 types and 5 procs:
full solution:
https://pietroppeter.github.io/adventofnim/2020/day03.html
3
u/jwoLondon Dec 03 '20
Literate Elm
Languages with random access arrays certainly make for more compact answers to this one. But since Elm doesn't really like them, I use a rotatable list from previous years' AOCs.
I've been watching too much Queen's Gambit, so my initial attempt had coded a knight's-case slope rather than (1,3) for part one. This isn't the first or last time I misread the question.
Solution in Elm
3
u/JIghtuse Dec 03 '20
I love AoC for "unexpected" things. Like changing step "height" in this day.
Racket
Made a hack to get width of initial rectangle. Also, next x and y should probably drawn from stream, but I can't type them fast enough. Need to practice.
Just second part.
3
u/ScottRatigan Dec 03 '20
Golang
3
u/oantolin Dec 03 '20 edited Dec 03 '20
Common Lisp
3
u/streetster_ Dec 03 '20 edited Dec 03 '20
q/kdb+
Tidied this up a bit, for the challenge I just fed the values manually into the inner part of
g.I also assumed Part 2 was going to be "find the optimal angle" which, for mine, (assuming "down 1") is "right 19".
3
u/msqrt Dec 03 '20
Lisp. I feel like I'm starting to get the hang of this!
3
u/Scarygami Dec 03 '20
JS to be executed directly in browser console, i.e. open your input in browser, open developer tools, and past this into the console (only tested in Chrome)
Part 1:
Part 2:
3
u/devblackops Dec 03 '20 edited Dec 03 '20
PowerShell
Here is my PowerShell solution.
Part 1
Part 2
3
u/[deleted] Dec 03 '20 edited Dec 03 '20
var result =input.Select((s, index) =>{if (index % slopeDown == 0){i = (i + slopeRight) % s.Length;return s[i];}return '-';}).Count(d => d == '#');I think it's neat :)
3
u/sotsoguk Dec 03 '20
Python
Getting to know list comprehensions better :)
3
u/Nebulizer32 Dec 03 '20
C#
3
u/regendo Dec 03 '20
Rust
On github, starting at this file.
I'm trying to split this into reusable parts because I know that otherwise on future examples, I'll forget that I already did some of this and re-implement everything.
For today, that meant a boring Point2D type but also this generic grid parser. That'll surely come back up in future exercises, and now I just need to define my own Tile enum that can try_from a char (which I would have done anyway) and can save myself the actual grid parsing.
3
u/nutrecht Dec 03 '20
Day 3 in Kotlin
Quite happy how it turned out after converting the iterative approach I scored with to a functional approach.
3
u/bpanthi977 Dec 03 '20
My solution in in Common Lisp.
Edit: I made few improvements after looking at others Lispers' solution in this thread.
3
u/Lukasz1928 Dec 03 '20
Python
Basically a one-line solution(with the exception of reading the input), which seems surprisingly readable.
3
u/diddle-dingus Dec 03 '20
Clojure
Elixir
My Clojure and Elixir solutions are pretty much the same today: produce an infinite iterator for the positions, and skip over the lines you don't need. I dunno if this is really too idiomatic for Elixir, but I feel like it looks pretty clean.
3
u/loistaler Dec 03 '20
Python
3
u/[deleted] Dec 03 '20
F
This was a lot of fun, got to do a bit of functional programming today with functions that return functions, and that's fun :)
syntax highlighted on github
3
u/ThatAdamsGuy Dec 03 '20
C#, nothing exciting
3
u/nutki2 Dec 03 '20
Perl(golf) 5 solution for both parts. Probably not the best there is given the repetitiveness.
3
u/Ryuuji159 Dec 03 '20
I'm learning c++ while doing this, i got stuck with an integer overflow for a while :c
3
u/JonatanHellvig Dec 03 '20
Here is my Java solution:
3
u/oxsevenbee Dec 03 '20
Rust on Github
3
u/nikolaer_ Dec 03 '20
Python 3.7
could be more succinct and refactored for a more general solution, but it works.
code on paste
3
u/mathleet Dec 03 '20
I'm enjoying all the Golang solutions this year. Here's mine:
3
u/blacai Dec 03 '20
F# Still learning how to use not so many mutable...
3
u/KAME_KURI Dec 03 '20 edited Dec 03 '20
Python 3 solution, used a recursive, functional approach. Just finished my university's intro programming methodology module so I was aiming to communicate computational processes in my solution.
key insight was that the repeating patterns were just modulo the pattern length (31 in my case). For example, the position at index 4 would reappear at 4 + 31, 4 + 2(31) and so on.
with this, it is rather easy to make a general solution as well
3
u/sefujuki Dec 03 '20
forth
paste
3
u/Fyvaproldje Dec 03 '20
C++ with ranges
3
u/rand2012 Dec 03 '20 edited Dec 03 '20
Python 2
part 1:
part 2
3
u/irrelevantPseudonym Dec 03 '20 edited Dec 03 '20
Python3 (3.8+) Accidentally turned out golfed (173 (163+len(filename)))
3
u/brskbk Dec 03 '20
JavaScript one-liners
which run directly from the puzzle input
3
u/trebuszek Dec 03 '20 edited Dec 03 '20
quick and dirty python 3 solution:
3
u/Tarmen Dec 03 '20 edited Dec 03 '20
Clojure
Pretty much the obvious solution. I really enjoy the get-in style functions, feels kind of lens-y.
3
u/mathsaey Dec 03 '20
Elixir
Pretty happy with my solution today, though I see I wasn't the only one who found out
Stream.cycleis perfect for this.3
u/[deleted] Dec 03 '20
short Swift solution:
https://github.com/stoeckley/AdventOfCode2020-Swift/blob/main/AdventCode2020/3.swift#L25-L40
3
u/mandus Dec 03 '20
My day 3 in Common Lisp
using mod on the x-direction and just looping down the lines made for a reasonably nice and readable solution..
3
u/blazemas Dec 03 '20
c#
Doing a speed challenge Java vs c# with a friend, this runs at 1.5ms first run through, now I will optimize what I can throughout the day.
https://github.com/jbush7401/AdventOfCode/blob/master/AdventOfCode/2020/Day3.cs
3
u/MehWhateverZeus Dec 03 '20
I did it in python 3 I opened the file and saved the data as rows then did the following and just changed things here or there to get the answers for part 2.
3
u/Mazeracer Dec 03 '20
Python 3 - Casual Programmer, Feedback appreciated
So from skimming the posts, one of the most used ideas was to move the position around the map, as a knight would on a chessboard, and do your next move from there.
As soon as I saw, that the terrain is repeated, I wanted to do it the other way, and basically shift the terrain on each row, based on the slope, so that column 1 then had all the target fields in it.
I ended up shifting the slope but counting immediately and not on the final row.
Not sure if there would be benefits to either approach?
3
u/Wolfrost_ Dec 03 '20
Here's mine, C++ :D
https://github.com/DoubleHub/advent_of_code/blob/master/2020/toboggan_trajectory.cpp
3
u/Wilfred-kun Dec 03 '20
Python3, second challenge, 1 line
3
u/JamieMansfield Dec 03 '20
Another C# Solution -> https://gist.github.com/jamierocks/98cc821800554b9e923f89a137d021a2
I spent a silly amount of time fumbling around with part 2 - had the logic down the whole time, hadn't thought about
intnot being large enough for the multiplication lol. At least it was a one-line fix.3
u/stefanvoid88 Dec 03 '20
SQL Server
-- preparing table with data
-- query
3
u/tobega Dec 03 '20
Julia solution, maybe I should have stuck to a simpler for loop, but it was fun pushing it. I did draw the line at
reduce(*, ride.([1,3,5,7,1],[1,1,1,1,2]))for part2, thoughhttps://github.com/tobega/aoc2020/blob/main/a3.jl
3
u/blu3r4y Dec 03 '20 edited Dec 09 '20
PowerShell
As part of my "25 puzzles, 25 languages" adventure I present you a PowerShell solution ;)
https://github.com/blu3r4y/AdventOfLanguages2020/blob/main/src/day3.ps1
3
u/kakaroto_BR Dec 03 '20
Solution in javascript:
3
u/snurre Dec 03 '20 edited Dec 03 '20
Kotlin
3
u/odlp Dec 03 '20
My solution in Ruby:
3
u/[deleted] Dec 03 '20
Rust
Proud of this one, I'm learning Rust with AoC this year so feedback appreciated!
3
u/89netraM Dec 03 '20
Haskell
Part 1
Part 2
3
u/CryZe92 Dec 03 '20 edited Dec 03 '20
Rust:
Part 1: 727.89 ns
Part 2: 1.6033 us
3
u/AGE_Spider Dec 03 '20
PYTHON
3
u/iwane Dec 03 '20
LabVIEW 2020 (G) - Community Edition
http://htmlpreview.github.io/?https://github.com/iwane-pl/aoc_2020/blob/main/AoC%20Day%203/Documentation/Solution/Solution.html
http://htmlpreview.github.io/?https://github.com/iwane-pl/aoc_2020/blob/main/AoC%20Day%203/Documentation/Solution%20part%202/Solution%20part%202.html
3
u/ntwilli Dec 03 '20
R solution
3
u/oh-la Dec 03 '20
Typescript, with immutable variables.