r/adventofcode • u/daggerdragon • Dec 01 '21
SOLUTION MEGATHREAD -🎄- 2021 Day 1 Solutions -🎄-
If you participated in a previous year, welcome back, and if you're new this year, we hope you have fun and learn lots!
We're following the same general format as previous years' megathreads, so make sure to read the full description in the wiki (How Do the Daily Megathreads Work?) before you post! Make sure to mention somewhere in your post which language(s) your solution is written in. If you have any questions, please create your own thread and ask!
Above all, remember, AoC is all about having fun and learning more about the wonderful world of programming!
To steal a song from Olaf:
Oh, happy, merry, muletide barrels, faithful glass of cheer
Thanks for sharing what you do
At that time of year
Thank you!
NEW AND NOTEWORTHY THIS YEAR
- Last year's rule regarding
Visualizations has now been codified in the wiki - tl;dr: If your Visualization contains rapidly-flashing animations of any color(s), put a seizure warning in the title and/or very prominently displayed as the first line of text (not as a comment!)
- Livestreamers: /u/topaz2078 has a new rule for this year on his website: AoC > About > FAQ # Streaming
COMMUNITY NEWS
Advent of Code Community Fun 2021: Adventure Time!
Sometimes you just need a break from it all. This year, try something new… or at least in a new place! We want to see your adventures!
- Your newest AoC-related project
- The Internet is a series of tubes, after all
- Push hardware and/or software well past its limit and make it do things it wasn't designed to do
- e.g. solve puzzles on a TI-89 or inside video games, etc.
- An AoC mug filled with the latest results from your attempts to develop the ultimate hot chocolate recipe
- A picture of your laptop showing AoC while you're on a well-deserved vacation at a nice resort on a tropical island
More ideas, full details, rules, timeline, templates, etc. are in the Submissions Megathread.
--- Day 1: Sonar Sweep ---
Post your code solution in this megathread.
- Include what language(s) your solution uses!
- Here's a quick link to /u/topaz2078's
pasteif you need it for longer code blocks. - 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 code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.
64
u/relativistic-turtle Dec 01 '21
IntCode :)
Note 1: Assumes input is given in ASCII-format. I.e., the depth values are given as ASCII-coded strings ("123") delimited by newline ("\n", ASCII-value 10). See IntCode-problems 17, 21 and 25 of 2019.
Note 2: Assumes input is 2000 rows, as it was for me.
Note 3: I used my self-written (and quite ugly) "C lite" to IntCode-compiler to actually generate the IntCode-program
37
u/voidhawk42 Dec 01 '21 edited Dec 01 '21
APL once again this year!
EDIT: Also going to be doing Clojure this year, here's day 1. I think Clojure should be pretty nice for problems that require exotic datastructures that aren't in APL - like, uh, hash maps.
68
u/Smylers Dec 01 '21 edited Dec 31 '21
Vim keystrokes. If you haven't encountered this sort of solution before, this isn't a program in Vim's scripting language, but simply normal-mode keystrokes that you type in to manually transform the input into the solution:
Load your input file, type in the above, and the number of lines displayed by
⟨Ctrl+G⟩is your part 1 solution.For part 2, press
uenough times to get back to your starting input, then:Again, the number of lines is your answer.
How's it work? In part 1, the body of the ‘main loop’ is
jyiwk@0⟨Ctrl+X⟩j. You can watch this one keystroke/command at a time as you type it:jgoes down to the line below the current one.yiwyanks the word the cursor is on, that is the number on that line. (Other yankings are possible, butyiwis often the most useful one in Advent of Code, working regardless of whether the number is one or multiple digits, and regardless of where the cursor is in the number.) No register has been specified, so by default Vim yanks into register0.kgoes back to the line we were on.@0runs the contents of register0as a keyboard macro. If theyiwyanked “200” (as it will in the sample input), then@0behaves as though you now typed200in normal mode.⟨Ctrl+X⟩is Vim's subtraction command.200⟨Ctrl+X⟩would subtract 200 from the number the cursor is on. So@0⟨Ctrl+X⟩subtracts the number that was yanked — that is, the number on the next line, turning “199” into “-1”.jmoves down a line again, for the next time round the loop.qaqqa…@aq@ais the loop infrastructure:qabegins recording keystrokes to thearegister. The finalqstops the recording. So all the above commands for the subtraction get stored ina.@ais the command for running the keystrokes in registera. So after recording them,@awould run the second iteration of the loop.q, there's another@a. The keyboard macro finishes by usingkto move on to the next line then invoking itself again on that line. So after recording,@asets it off on the second line, and then it continues looping through all the lines.kto move to the line below will fail (and possibly beep), thereby exiting the loop.@ain at the end of the macro, we need to type it when recording it. But we don't want Vim to run whatever nonsense happened to already be in registera. So theqaqat the beginning first starts and then immediately stops recording into registera, that is it clears it out. So the first@atyped is a no-op at that time: Vim happily runs all zero of the keystrokes in that register as we're typing it, but saves the@akeystrokes themselves into the macro currently being recorded, and by the time@aruns, registeraobviously contains itself.Why all this subtraction anyway? Well, every time the depth increases, subtracting the next depth from the current one will give a negative number. So having subtracted each pair of lines in turn, the answer is the number of negative numbers in the buffer. So get rid of all the lines not containing a negative number with
:v/^-/d, and the number of lines remaining in the file is the number of times the depth increased. You might have a Vim status line displaying that anyway, but if not⟨Ctrl+G⟩will show it.:v/PATTERN/COMMANDis an Ex command which runs the specified Ex command on every line of the file that doesn't match the pattern. (It's the opposite of:g//, which does it on lines that do match. To remember them think of:gbeing a bit like the Unixgrepcommand, and:vinverting that, likegrep -v.)/^-/matches all lines which start with a minus sign — which in a text editor is way easier than interpreting the lines numerically and comparing them to zero — and:deleteor:dis the Ex command for deleting the current line (try it!). In Vim you'd usually achieve that in normal mode withdd, but:vrequires an Ex-style command after the pattern, so we use:d(well,d, because the colon is implicit) here. And that's the answer.For part 2, there's the same loop infrastructure as above, but this time using
@b. In each loop iteration we go down twice and yank the number there into thezregister (jj"zyiw), up one line and yank into the default register (kyiw), then up again to the line we started on.⟨Ctrl+A⟩does addition, so@z⟨Ctrl+A⟩and@0⟨Ctrl+A⟩add the two yanked numbers on to the current one. So each number gets turned into the sum of that number and the following 2 — that is, a three-measurement sliding window.The loop crashes out when there aren't enough lines below to yank, leaving the bottom two original numbers and the cursor on the final line.
dkdeletes them and{moves the cursor to the start of the first line.At which point, with a list of sums of three-measurement windows, all we need to do is count the number of increases. This initial pass has effectively transformed the input into a part 1 problem. So just run
@afrom part 1 to calculate the answer (it's now effectively a function!), then do the:vthing again to display it.Any questions?
PS: Belated thank you to
/u/daggerdragonfor my ‘Heinous (ab)Use of Vim’ prize in last year's awards. I saw it a few days after Christmas and did appreciate it, but never got round to thanking you at the time; apologies.29
u/SirFloIII Dec 01 '21
Factorio Combinators
24
u/[deleted] Dec 01 '21
Regex
Regex advent of code, let's go. Count number of matches.
Part 1: https://regex101.com/r/vd634b/1
Part 2: https://regex101.com/r/kFYiy8/1
22
u/3urny Dec 01 '21
Brainfuck (infinite cell size)
16
u/meMEGAMIND Dec 01 '21
My first Advent of Code! My friend just introduced me to it yesterday. She's a novice programmer just trying to get as far as she can!
Me on the other hand, well... I can't code at all. I don't know any languages. BUT this challenge seemed super intriguing! So I decided to use what I know how to use: The Desmos graphing calculator.
We'll see how for I can get with this haha. I'm having fun!
Day 1 Solution:
https://www.desmos.com/calculator/ughpqquz4z
12
u/jaybosamiya Dec 01 '21 edited Dec 01 '21
APL solutions today are quite pleasing:
Explanation:
First line of code simply grabs the input file and parses as an array of integers, and stores it into the variable
n. Next line solves part 1, and the next part 2Both parts have a very similar solution, so let's look at part 1 first.
It is best read from right to left, so let's start there: take the input
nand rotate it once1⌽n(changinga b c d etoe a b c d); this gives us a new array that we can perform a pairwise less-than comparisonn < 1⌽nto obtain an array of bits. We then flip the whole array around (using the⌽: changesa b c dtod c b a), so that the first element becomes last, and vice-versa. Then we drop the first bit (previously last bit) using1↓since it is an extraneous comparison (in the challenge, this would mean comparing the first element against the last element; and since we don't have a circular buffer, we don't care for this). Finally, we simply take the sum over these bits using+/; since APL represents bits as integers, this is equivalent to counting the number of 1 bits. Putting this all together, we get the APL program+/1↓⌽n<1⌽nNow for part 2, it is important to recognize that the summing stuff is irrelevant. In particular, the sum of 3 numbers
b + c + dis greater than the suma + b + cif and only ifa < d, so we simply need to look at windows of size 4, rather than windows of size 2 like before. This means that our rotation and dropping counts just change from1to3, and we obtain the expected result with only 2 bytes changed from the previous solution12
u/GaloisGirl2 Dec 01 '21
COBOL
11
u/ElCthuluIncognito Dec 01 '21 edited Dec 01 '21
Haskell (Part 2)
Anyone else realize that for part two you just had to compare every value with the one 3 indexes ahead?
i.e. compare 0 to 3, 1 to 4, 2 to 5, and so on, counting the number of times the latter value is higher.
The idea is that the middle two values of any two consecutive windows is shared between the windows, effectively nullifying them in the comparison.
Edit: The solutions that zip against the truncated list (e.g.
zipWith (<) xs (drop 3 xs)) are much more elegant! Hopefully at least mine has the value of showing off the pattern matching of Haskell.10
u/polroskam Dec 01 '21 edited Dec 02 '21
My Python solution using Pandas Series
5
u/DFreiberg Dec 01 '21 edited Dec 01 '21
Mathematica, 1979 / 513
Note to self: when saving an input, be sure not to leave out the last line.
Part 1:
Part 2:
[POEM]: Stalling The Seven Seas
Today, we lost the sleigh keys on the ocean:
A tragedy we'll need a month to right.
They're truly lost; we haven't got a notion
Of where they got to after leaving sight.
And so from duty verging on devotion
We'll start our month-long enterprise tonight.
We certainly won't rummage in slow-motion...
(...okay, we just like submarines, alright?)
We'll need a month, at least, to find the keys
Which sadly we misplaced beneath the seas.
5
u/CodeIsTheEnd Dec 01 '21
Ruby: 1:37/3:44, 370/280
Here's a recording of me solving it, and the code is here. I stream myself solving every day's problem on Twitch!
Pretty standard Day 1. Might've made the leaderboard for Part 1 if I didn't get a 504, who knows though. Definitely not for Part 2.
5
u/trollerskates1 Dec 01 '21 edited Dec 01 '21
Scala using
slidingEdit: fixed formatting
5
u/DaveTCode Dec 01 '21
I don't think anyone else has done this before. So here's day 1 part 1 & 2 implemented in pure LLVM IR. https://github.com/DaveTCode/aoc2021-llvm/blob/main/day1/day1.ll
5
u/masterarms Dec 01 '21 edited Dec 02 '21
Kotlin:
5
u/GalaxyLittlepaws Dec 01 '21
My first-ever Advent of Code!
I'm trying to get my skills with PHP up for a personal project, so that's what I decided to work with.
I can't seem to figure out code boxes on Reddit at the moment, so here are the links!
Part 1
Part 2
7
u/Kantaga Dec 01 '21
APL
Part 1:
+/¯1↓x<1⊖xPart 2:
+/¯3↓x<3⊖x4
u/kolcon Dec 01 '21 edited Dec 01 '21
Python - Pandas
I took it as exercise for Pandas…
https://github.com/LubosKolouch/AdventOfCode_2021/blob/main/day_1.py
7
u/quantumcuckoo Dec 01 '21
Honestly, I just did this one in Excel. Shoot me.
3
u/A-UNDERSCORE-D Dec 01 '21 edited Dec 01 '21
Python (but soon others)
Quick and fun! though I did do a glorified len for part 1 initially!
https://github.com/A-UNDERSCORE-D/aoc2021/blob/main/aoc/python/one.py
Rust
Im still learning rust, but it makes me do bad things (like oneliners)
https://github.com/A-UNDERSCORE-D/aoc2021/blob/main/aoc/rust/src/days/one.rs
Golang
This was the last of the three I did. It uses generics and a some other clever things!
https://github.com/A-UNDERSCORE-D/aoc2021/blob/main/aoc/go/one/01.go
3
u/[deleted] Dec 01 '21
Common Lisp - definitely won't be the most concise solution in this language on this thread! I picked it up for the first time yesterday and feel like I'm brutalizing the language a bit
3
u/semicolonator Dec 01 '21
Python
https://github.com/r0f1/adventofcode2021/blob/master/day01/main.py
3
u/gijo57 Dec 01 '21 edited Dec 01 '21
No regex so far ;). I get Vietnam flashbacks from last year every time I write "import re" in my python script.
My python solution:
Python solution
3
u/TommiHPunkt Dec 01 '21 edited Dec 01 '21
Matlab:
not overkill at all to use
tallbuiltins here :D2
u/Kermitnirmit Dec 01 '21 edited Dec 01 '21
Python 3 Pretty simple day 1! I took so darn long to remember how pandas worked. My solution / used zip to shift and compare
as well as using pandas' rolling sum feature for part 2.[Edit] Realized that there are common values in the sum for part 2, so you only need to check elements 3 apart, used zip for that too.
2
u/Chrinkus Dec 01 '21
My C Solution
Last year I planned to do the event in C but abandoned it pretty early. We're going all the way this year, baby!
2
u/Swynndla Dec 01 '21 edited Dec 01 '21
Nim
2
u/uas90s Dec 01 '21 edited Feb 06 '22
NodeJS
Part 1 const fs = require("fs");
Part 2
2
u/Cpt__Cookie Dec 01 '21 edited Dec 01 '21
Python:
GitHub
2
u/tftio Dec 01 '21 edited Dec 01 '21
My Haskell solution (using Justin Le's scaffolding):
OK, fine, how do you get this godforsaken editor to handle a code block? FFS.
2
u/ecrooks Dec 01 '21
IBM Db2 LUW (11.5) SQL:
More details including docker container to run available here: https://github.com/ecrooks/aoc2021_SQL
2
u/Awkward-Camera-111 Dec 01 '21
I don’t know how on earth I can add code so I’m just gonna leave the link to my GitHub repo:
python 🐍🐍🐍
https://github.com/Mike920-dev/advent-of-code-2021
49
u/Chitinid Dec 01 '21 edited Dec 01 '21
Python
Part 1:
sum(x < y for x, y in zip(nums, nums[1:]))Part 2:
sum(x < y for x, y in zip(nums, nums[3:]))EDIT: optimized based on comments
26
u/Mathgeek007 Dec 01 '21 edited Dec 01 '21
1:08/2:09. 112/46 Excel.
Video of live process here!
It was a two-column solution;
=SUM(RC[-1]:R[2]C[-1])then in the next column;
=R[1]C[-1]>RC[-1]Then I summed that TRUE in that column and got the answer. Part 1 is the exact same, but without that first formula.
15
u/death Dec 01 '21
Day 1 solution in Common Lisp
My initial solutions were the following, but decided to go for a generalized solution in the gist.
14
u/jitwit Dec 01 '21 edited Dec 01 '21
J Programming Language
If you're not familiar with J, here's the explanation:
+and<above are addition and less than comparison, as you'd expect./is an adverb (or more commonly, operator) called insert that takes its operand and creates a verb (function) that reduces over its input. so+/sums its argument.\is also an adverb called infix that takes a verb and applies it over infixes of a certain length of its right argument. So,+/is a verb, and3 +/\ ingets all the sums over length 3 windows ofin.2 </\ infinds all the times the depth increases. And+/ 2 </\ intotals how many times the depth increases.13
u/4HbQ Dec 01 '21 edited Dec 01 '21
Python, golfed to 70 bytes:
The trick for part two (comparing
x[i:i+3]tox[i+1:i+4]) is that we only need to comparex[i]withx[i+3], because values forx[i+1]andx[i+2]are shared by both windows:13
u/Tails8521 Dec 01 '21
Motorola 68000 assembly (On a Sega MegaDrive)
Not gonna bother optimizing it to O(1) memory usage, it fits easily in the 64KB of the Sega MegaDrive as it is.
12
u/emilhvitfeldt Dec 01 '21
R
This problem fits perfectly into what R is good at. Native diff function with lag functionality
12
u/Chebtis Dec 01 '21 edited Dec 06 '21
Rockstar
Probably not doing any other days in this but was fun learning it after seeing some others post on here last year.
Part 1: https://codewithrockstar.com/online?source=https://raw.githubusercontent.com/kloo/aoc2021/main/01/1a_2021.rock
Part 2: https://codewithrockstar.com/online?source=https://raw.githubusercontent.com/kloo/aoc2021/main/01/1b_2021.rock
11
u/miran1 Dec 01 '21 edited Dec 01 '21
Python, one-liner for both parts:
Repo: https://github.com/narimiran/AdventOfCode2021
11
u/ActualRealBuckshot Dec 01 '21
Python and numpy one liners without any messy functions.
10
u/minikomi Dec 01 '21
Clojure
10
u/Iain_benson Dec 01 '21
Excel
With the data pasted the data into row 2 onwards, the following formulae work for parts 1 & 2 respectively
Part 2 is taking advantage of the fact that
B+C+D > A+B+C = D > A, which simplifies the problem quite considerably.9
u/schubart Dec 01 '21 edited Dec 01 '21
Rust
GitHub
9
u/reddit_clone Dec 01 '21
Common Lisp
9
u/pietroppeter Dec 01 '21 edited Dec 01 '21
🎄👑 Nim
blogging about a nim solution and trying (unsuccesfully - hopefully will fix later; edit: viz fixed) to make a visualization:
https://pietroppeter.github.io/adventofnim/2021/day01.html
9
u/jayfoad Dec 01 '21
Dyalog APL
9
u/Groentekroket Dec 01 '21
Easy start, wonder how far I will come this year:
9
u/sotsoguk Dec 01 '21
Python 3
This year I try to be more pythonic and make my code clearer. Solution to part 1 and 2:
9
u/tomflumery Dec 01 '21 edited Dec 03 '21
05ab1e -
part 1 (6 chars)
part 2 (10 chars)
9
u/reckter Dec 01 '21 edited Dec 02 '21
intcode!But only the first part, because I am lazy 😅
But I didn't exactly write this by hand, but instead compiled it from what I call "intScript", in which it looks like this:
This gets compiled to an assembler language first:
I feed it the input as ascii chars and parse the integers and compare them.
8
u/obluff Dec 01 '21 edited Dec 01 '21
Bash
part one
part two
8
u/_jstanley Dec 01 '21 edited Dec 10 '21
SLANG
(Homemade language on a homemade CPU)
I stuffed up part 1 because I initialised "prevdepth" to 0xffff but I forgot that my ">" operator is signed, so this counts as -1, so the first element is greater than it.
Apart from that, I found that my solutions ran much slower than expected. Part 1 takes about 50 seconds to run.
I've since profiled it and discovered that 50% of execution time was spent doing system calls to read characters of input. I do have a buffered IO library to solve this problem, but I didn't think the AoC inputs were big enough to make any difference. Turns out they are! After switching to buffered IO it runs in 23 seconds, of which 70% is related to integer parsing. Some of the integer parsing stuff is already optimised assembly language, but some of it is not.
There's a lot of "parse a large number of integers" in the input phase of Advent of Code problems, so for future days I'm going to try to remember to use my buffered IO library, and I'm going to try to spend some time today optimising the slower parts of integer parsing.
https://www.youtube.com/watch?v=ZLF8bWWw9FA
https://github.com/jes/aoc2021/tree/master/day1
8
u/__Abigail__ Dec 01 '21 edited Dec 01 '21
Perl
As usual, an easy starter on day 1.
Now,
$count1and$count2contain the answers for part 1 and part 2.8
u/NohusB Dec 01 '21 edited Dec 01 '21
Kotlin
Part 1
Part 2
8
u/Jaik_ Dec 01 '21
Rust
You could definitely make this shorter but I think this is a good balance for readability.
8
u/janiczek Dec 01 '21
APL
p1←+/2</in
p2←+/2</3+/in
Twitter thread explaining it: https://twitter.com/janiczek/status/1465969017089363969?t=byNxxCkU5sZp0WS47-fW3g&s=19
7
u/ssalogel Dec 01 '21
python 3
7
u/[deleted] Dec 01 '21
Retina
https://tio.run/##K0otycxLNPz/P9pA1zJWm0vFQCvRGkRwaSRqax7aFmPIZcdll/j/PwA
7
u/0rac1e Dec 01 '21 edited Dec 02 '21
Raku
Explanation: -
@depths[1..*, *]returns 2 lists, the first one starting from index 1, and the second from 0.[Z>]is the zip meta-operator, combined with greater-than, so it will zip the two lists together, compare the pairs, and return a list of Booleans[+]reduces the list of Booleans with addition. Booleans are an enum where True is 1 and False is 0.I originally solved part 2 by first creating 3 lists starting from the 2nd, 1st, and 0th index, and zipping together with plus, like so
Then I could just compare each subsequent element as in part 1, but it appears that's not even required. I can just compare each item with the item that's 2 indices ahead. I don't fully grasp why this works, maybe some mathematical truth that escapes me. (edit: thanks u/polettix for the explanation below)
Raku has a handy
.rotormethod on iterables that makes doing sliding windows very easy. I could have just as easily solve it by leaning on that method but... I've been digging into array languages this year (mostly J... see my J solution further down) and I kinda tackled it how I might do it in an array language.Here's a alternate Raku solution using the
.rotormethod.--
J Language
I'm a relative amateur with J but this is what I came up with
Or using the "trick" where I don't bother doing the 3-sum
Note: See jitwit's post for a much nicer J solution.
7
u/Mayalabielle Dec 01 '21
Rust, windows ftw.
7
u/kubav27 Dec 01 '21
Rust, both stars computed by the same function
7
u/AharonSambol Dec 01 '21 edited Dec 01 '21
My one lined python solution
7
u/paul2718 Dec 01 '21
C++ has a function to solve this problem.
inner_product applies a binary function between elements of the two input ranges, and then a binary function between the initial value and the result of the first function. The two input ranges are simply different views of the puzzle input, the first function returns '1' (true...) if the second value is greater than the first, the second is 'plus'. transform_reduce is similar, but doesn't guarantee the order over the range, and it hurts my head to figure out whether that matters.
7
u/[deleted] Dec 01 '21 edited Dec 01 '21
05ab1e
part1:
Explanation:
| -- push input as array on the stack
D -- Duplicate top of stack
Á -- Rotate right once
ø -- zip
ε -- map
` -- elements of list onto stack
.S -- compare
} -- end map
1.$ -- drop first element of array
ʒ -- filter
0› -- larger than 0
} -- end filter
O -- sum
-- Implicit output
part2:
Part2 is in large part the same as part 1 just that I rotated by 3 instead of 1 by using
3 -- push on stack
( -- negate
._ -- rotate left by
instead of Á
7
u/doughfacedhomunculus Dec 01 '21
Python and Numpy
Rather pleased with these one-liners. Probably some similar solutions already.
7
u/ssnoyes Dec 01 '21
It's like Python 3.10's itertools and more_itertools were made for today:
7
u/gauauuau Dec 01 '21
6502 Assembly (targeting the NES)
https://pastebin.com/T2QheTp6
Only the code for the solution is in that dump, not the entire dump of source needed to power on the machine, get it ready, clear the screen, display the answer, etc.
6
u/phil_g Dec 01 '21 edited Dec 01 '21
Common Lisp, 871/308
Literally just typing things at the REPL. I'll go back later today and write a formal implementation. Part 1 was:
The first line there uses my prewritten functions to get the input as a list of integers.
Part 2 was:
It's a mixture of FSet code with native lists, just because I remembered how to use
filterthe fastest.Edit:
(fset:size (fset:filter ...))would be simpler as(count-if ...).Edit 2: Formal code here. The essence of it, though, is
(gmap:gmap :count-if #'< (:list depths) (:list (nthcdr window-size depths))).window-sizeis 1 for part 1 and 3 for part 2.6
u/dtinth Dec 01 '21 edited Dec 01 '21
I made 2 silly mistakes (e.g. forgot to convert to int and used the wrong comparison operator). Next time I will remember to test with example data first 😄
Edit: Thanks to the suggestions by u/gurgeous, u/BluFoot, u/442401, the above can be improved like this:
6
u/lukechampine Dec 01 '21 edited Dec 01 '21
slouch
EDIT: as others have pointed out, a simpler solution to part two is:
6
u/wace001 Dec 01 '21
Kotlin 266/467:
Where the ints function is just a function that reads all ints of a String :)
6
u/autid Dec 01 '21 edited Dec 01 '21
FORTRAN
Back after missing last year. Still can't resist doing janky fortran.
edit: cleaned up the counts. previously was
6
u/rtbrsp Dec 01 '21
Solved using my own language (Riff)
Part 1
Part 2
6
u/kimvais Dec 01 '21
Once again, F#
Seqmodule made things trivial.F#
6
u/raevnos Dec 01 '21
Using Sqlite's window functions: paste
6
u/brunocad Dec 01 '21
Haskell (Type level only). Could be nicer if I used ghc 9 since they added the <? type family so I wouldn't have to do it myself
6
u/Swynndla Dec 01 '21
nim
6
u/AltPapaya Dec 01 '21
My Python solution
6
u/timvisee Dec 01 '21
Rust
Part 1
Part 2
6
u/Littleish Dec 01 '21 edited Dec 01 '21
Python 3.10: Using Pandas
6
u/MichalMarsalek Dec 01 '21
Nim
using my templates
6
u/smokebath Dec 01 '21
Python 3.10, full code on the gist but important stuff below
I see from other solutions I could have simplified part 2 to 'zip(ins, ins[3:])' instead of the three chunks I used. This subreddit is a great way to learn :)
6
u/censustaker1 Dec 01 '21
ghetto perl solutions
6
u/gwillicoder Dec 01 '21
Here is my solution in Python:
6
u/ShadowwwsAsm Dec 01 '21
In nasm, I'll do as many days as I can
part1
part2
6
u/LionSuneater Dec 01 '21 edited Dec 02 '21
[Python] Convolution ftw.
edit: slightly faster with np.sum and np.diff for line 4...
6
u/5stars_3stars Dec 01 '21
Clojure, both parts:
Assumes
inputto be a vector of numbers.6
u/bottlenix Dec 02 '21
Perl
Was able to do this with one-liners for each Part. This will probably be the only day I can solve the puzzle on the day it is published!
I noticed that in Part 2, you can ignore the two measurements that overlap the two windows to slightly simplify the calculation at the expense of clarity.
6
u/stevelosh Dec 02 '21
Common Lisp
5
u/jonathan_paulson Dec 01 '21
I got 12th on part 1 and 55th on part 2. Video of me solving: https://youtu.be/pkLfyRwDMMw. Python3 code: https://github.com/jonathanpaulson/AdventOfCode/blob/master/2021/1.py
Tried using a template, but I think it made me slower for part 2 by encouraging iterating over lines instead of just reading them into a list.
5
u/rabuf Dec 01 '21
Common Lisp
I may do it again in another language, and there are cleaner ways to do this, but this is where I'm starting today.
A more functional approach (implemented after submitting my answers) is to use
countandmap:5
u/waffle3z Dec 01 '21
Lua 79/24,
getinput()retrieves the input text for the day corresponding with the filename5
u/kbielefe Dec 01 '21
Scala 3
Have kind of a cool input parser library this year. I tell it I want input as a
List[Int]and it pulls in the right type classes to parse it as such.5
u/bcgroom Dec 01 '21
Elixir
Feels good to be back! Decided to do Elixir again since it was so much fun last year. I also tried to do day 1 as fast as possible, kind of struggled with the windowing in part 2 and got just over 17 minutes, pretty happy with that. I cleaned it up a lot and this is what I came up with:
Full Code
5
u/clouddjr Dec 01 '21 edited Dec 01 '21
Kotlin and its built-in window function
5
u/drmattmcd Dec 01 '21
Python with numpy:
5
u/t-rkr Dec 01 '21
Perl
Link to Code
5
u/lynerist Dec 01 '21
Golang commented solution
https://github.com/lynerist/Advent-of-code-2021-golang/blob/master/Day_01/day01_b.go
5
u/Nysed17 Dec 01 '21
C
Part 1:
Part 2:
5
u/damyvv Dec 01 '21
Ruby
5
u/EmotionalGrowth Dec 01 '21 edited Dec 02 '21
><>
A fishy day 1.
The stack was manually initialised with the input.
5
u/imbadatreading Dec 01 '21 edited Dec 01 '21
Python:
5
u/Happy_Air_7902 Dec 01 '21
F# solution:
5
u/xPaw Dec 01 '21
Part 2 is simple because due to how sliding window works, you only need to compare every 3rd element (as it will only differ, and the other two numbers will be the same in both windows). As such, you don't need to zip or anything:
C#:
5
u/colombo15 Dec 01 '21 edited Dec 01 '21
C# - Generalized solution for both problems
5
u/ejuo Dec 01 '21
awk
part 1
part 2
5
u/maeevick Dec 01 '21
My Naive Haskell Solution: https://github.com/Maeevick/adventofcode2021/blob/main/src/D1.hs
5
u/_AngelOnFira_ Dec 01 '21 edited Dec 01 '21
Rust. Not my submitted solution, but I really like making double use of
windowsfor part 2.5
u/rakkie20 Dec 01 '21
Rust
5
u/deadthoma5 Dec 01 '21
Not sure if this is mentioned before, here is a shortcut for Part 2:
current window - previous window = (x3 + x2 + x1) - (x2 + x1 + x0) = x3 - x0
So, you don't have to sum over three numbers for the moving window. You can find the difference across two numbers which are further apart, since intermediate terms common to both moving windows cancel out.
5
u/complyue Dec 01 '21 edited Dec 01 '21
Numpy
Day 1
5
u/probablyfine Dec 01 '21 edited Dec 01 '21
JQ
Source and tests
5
u/ephemient Dec 01 '21 edited Apr 24 '24
This space intentionally left blank.
5
u/ecco256 Dec 01 '21 edited Dec 01 '21
Haskell
5
u/Jlobblet Dec 01 '21
D
I haven't seen a solution for D in the comments, so I thought I'd post mine here:
Quite a nice little solution if I say so myself. The full solution is here.
5
u/fmorel Dec 01 '21 edited Dec 02 '21
C# (with some implicit usings thanks to .NET 6):
Don't even need to add numbers together! Just compare the current one with the one 3 indexes behind.
5
u/WackoMcGoose Dec 02 '21 edited Dec 02 '21
It's my first time playing AoC, so I figured I'd go hardcore and solve things in a hacking simulator, EXAPUNKS to be specific. The game has its own "fantasy assembly" coding language, but custom puzzles are made in plain old JavaScript.
Puzzle solution here, top part is the .js file to create the puzzle itself, bottom part is the "EXAcode" to input in-game to get the solution. You have to paste your input data (comma-delineated) into
const INPUT_DATA = [/*foo*/];to make it work, though. This is what it looks like in-game.The first half was actually trivial to do entirely in EXAcode in-game. The second half... well... Exapunks truncates numbers to be in range [-9999, 9999], so I had to cheat a little and do the actual summing and comparison within JS itself. To keep to the spirit of my challenge though, it doesn't calculate the answer for you, only does the "too big numbers" math and expects the EXAs to interpret the results themselves.
Edit: I've discovered another awkward limitation built into the game... While it's possible to read a value from an arbitrarily long "file" (created by the puzzle itself), attempting to write a value beyond index 999 causes the EXA to throw a "FILE IS FULL" error and terminate. And it seems like all of the input data blobs are going to end up as way over 1000 units in length. ...Eh, I shouldn't be needing to write huge files in the game engine, only read from them (and the
createNormalFile()function seems to accept arrays of arbitrary length as long as all values are only strings or integers), so it's probably not a monkey wrench in my challenge...5
u/OculusRiftDriver Dec 02 '21
Excel:
Day 1 Puzzle 1:
=IF(A3>A2;1;0)
Day 1 Puzzle 2:
=IF(SUM(A3:A5)>SUM(A2:A4);1;0)
5
u/qaraq Dec 13 '21 edited Dec 14 '21
Rockstar
Because why the heck not.
I could have done better with my variable naming and poetic constants, but eh, at least it actually works.
Part 1:
Part 2:
9
u/ViliamPucik Dec 01 '21
Python 3 - Minimal readable solution for both parts [GitHub]
8
u/rossmacarthur Dec 01 '21
Here's mine using Rust iterators
4
u/u794575248 Dec 01 '21 edited Dec 01 '21
J Language
4
u/FriendLeather8450 Dec 01 '21 edited Dec 01 '21
Haskell
EDIT: I'm an idiot, here's a way simpler solution: paste
paste
4
u/oddrationale Dec 01 '21 edited Dec 01 '21
Here's my solution in F#.
Part 1:
Part 2:
4
u/gurgeous Dec 01 '21
Ruby. I was fast, but not as fast as you guys!
4
u/InKahootz Dec 01 '21 edited Dec 01 '21
C#
Part 1:
Part 2 (using C# 8 indexers):
ToIntArray()is just a string extension of mine.public static int[] ToIntArray(this string s) => s.Split().Select(int.Parse).ToArray();4
u/AP2008 Dec 01 '21 edited Dec 01 '21
Rust (64.688 us) paste
4
u/Hephlathio Dec 01 '21 edited Dec 01 '21
F#, 1618/763
Next time, let's not format path in the wrong way.
4
u/flwyd Dec 01 '21
Raku (neé Perl 6) 1957/2583 - Source including file reading and output printing
4
u/SuperSmurfen Dec 01 '21 edited Dec 01 '21
Rust (828/398)
Link to full solution
Easy start but I liked the problem. Pretty happy with my leaderboard placing, especially considering I had forgotten to log in to AoC which I realized as the counter hit 3 seconds! As always, the itertools crate is amazing. The
tuple_windowsfunction is perfect for this:So excited to be back again, third year in a row for me. Went back and finished almost everything, only 2018 left now.
4
u/[deleted] Dec 01 '21
Haskell
4
u/[deleted] Dec 01 '21
Elixir
https://github.com/sreedevk/advent-of-code/blob/master/elixir/2021/day01/lib/day01.ex
4
u/Rick-T Dec 01 '21
HASKELL
A calm start, as usual.
zipWithis the star of the show today:4
u/ethsgo Dec 01 '21 edited Dec 01 '21
Solidity
https://github.com/ethsgo/aoc
4
u/Imaginary_Age_4072 Dec 01 '21
Common Lisp 365/3502
Not that functional, but it works :)
Happy Advent of Code everyone!
4
u/BradleySigma Dec 01 '21
matlab
4
u/[deleted] Dec 01 '21
Ruby
https://github.com/sreedevk/advent-of-code/blob/master/ruby/2021/day1/main.rb
4
u/pepecze Dec 01 '21
C++
4
u/p_tseng Dec 01 '21 edited Dec 01 '21
Ruby
Okay so for this one all you have to do is just sort the input and... what do you mean I wasn't supposed to do it this way?
Yes this solution actually works. No you don't need to tell me the better way to do it, thanks :)
4
u/alach11 Dec 01 '21
Python3 - list comprehensions save the day!
4
u/Breadfish64 Dec 01 '21
C++
4
u/chunes Dec 01 '21 edited Dec 01 '21
This year, I'm hoping to write solutions in Factor, Red, QB64, and/or Forth, in that order of priority.
4
u/Klorec Dec 01 '21 edited Dec 01 '21
The R Language Quick and easy
4
u/iceraven101 Dec 01 '21
PowerShell
4
u/SgiathCZ Dec 01 '21 edited Dec 01 '21
Elixir
Part 1
Part 2
4
u/[deleted] Dec 01 '21 edited Dec 01 '21
Ruby
4
u/garciparedes Dec 01 '21 edited Dec 01 '21
Here is my 🦀 Rust solution for the 🎄 AdventOfCode's Day 1: Sonar Sweep
4
u/cocotoni Dec 01 '21
PowerShell
Part 1
Part 2
For part 2 a little trick is not to calculate the sum of the window, as 2 items in adjacent windows are always the same. So just compare the first element of preceding window to the last element of the next one.
4
u/Diderikdm Dec 01 '21
Python:
4
u/nutrecht Dec 01 '21
Kotlin solution
4
u/candurz Dec 01 '21
My solution in Adventlang 🎅
4
u/Wonderful-Bluejay-96 Dec 01 '21 edited Dec 01 '21
python3 - probably awful but at least they're oneliners
https://github.com/masmeert/advent-of-code/blob/master/2021/day01/main.py
4
u/hydraulictrash Dec 01 '21 edited Dec 01 '21
Cheeky JavaScript submission:
Similar to the other JS approaches, but uses a `reduce` instead
https://gist.github.com/nicholas-c/3302f25917d7b955881302174a45e49e
4
u/synack Dec 01 '21
Ada, not the simplest way, but I wanted to play with streams a bit.
https://github.com/JeremyGrosser/advent/tree/master/2021/src
4
u/6745408 Dec 01 '21 edited Dec 01 '21
Google Sheets
Part 1
Part 2 was a big derp for me
4
u/Steinrikur Dec 01 '21
I was going to stop doing bash, but...
4
u/Cpt__Cookie Dec 01 '21 edited Dec 01 '21
Rust:
GitHub
Edit: improved solution Thx to u/SDDuk
4
u/s3aker Dec 01 '21
Raku solution 2.
4
u/s96g3g23708gbxs86734 Dec 01 '21 edited Dec 01 '21
Python part2, how can I improve it?
Edit: the best solution is probably
:)
4
u/busdriverbuddha2 Dec 01 '21
Python 3, got it in two lines each.
Part 1:
Part 2:
4
u/diatone- Dec 01 '21 edited Dec 01 '21
Common Lisp, not sure how performant
subseqis like this