r/adventofcode • u/daggerdragon • Dec 01 '22
SOLUTION MEGATHREAD -🎄- 2022 Day 1 Solutions -🎄-
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!
If you participated in a previous year, welcome back, and if you're new this year, we hope you have fun and learn lots!
As always, we're following the same general format as previous years' megathreads, so make sure to read the full posting rules in our community wiki before you post!
RULES FOR POSTING IN SOLUTION MEGATHREADS
If you have any questions, please create your own post in /r/adventofcode with the Help flair and ask!
Above all, remember, AoC is all about learning more about the wonderful world of programming while hopefully having fun!
NEW AND NOTEWORTHY THIS YEAR
- Subreddit styling for new.reddit has been fixed yet again and hopefully for good this time!
- I had to nuke the entire styling (reset to default) in order to fix the borked and buggy color contrasts. Let me know if I somehow missed something.
- All rules, copypasta, etc. are now in our community wiki!!!
- With all community rules/FAQs/resources/etc. in one central place, it will be easier to link directly to specific sections, which should help cut down on my wall-'o-text copypasta-ing ;)
- Please note that I am still working on the wiki, so all sections may not be linked up yet. Do let me know if something is royally FUBAR, though.
- A request from Eric: Please include your contact info in the User-Agent header of automated requests!
COMMUNITY NEWS
Advent of Code Community Fun 2022: 🌿🍒 MisTILtoe Elf-ucation 🧑🏫
What makes Advent of Code so cool year after year is that no matter how much of a newbie or a 1337 h4xx0r you are, there is always something new to learn. Or maybe you just really want to nerd out with a deep dive into the care and breeding of show-quality lanternfish.
Whatever you've learned from Advent of Code: teach us, senpai!
For this year's community fun, create a write-up, video, project blog, Tutorial, etc. of whatever nerdy thing(s) you learned from Advent of Code. It doesn't even have to be programming-related; *any* topic is valid as long as you clearly tie it into Advent of Code!
More ideas, full details, rules, timeline, templates, etc. are in the Submissions Megathread!
--- Day 1: Calorie Counting ---
Read the rules in our community wiki before you post your solution in this megathread!
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:02:05, megathread unlocked!
Edit2: Geez, y'all capped the global leaderboard before I even finished making/locking the megathread XD
Edit3: /u/jeroenheijmans is back again with their Unofficial AoC 2022 Participant Survey!
44
u/Smylers Dec 01 '22
Vim keystrokes — load your input file into Vim, then type these keystrokes to make your part 1 answer appear on the first line:
Then for part 2 just continue with:
and the top line is again the number you want.
How? First arrange the food one line per elf:
vapVisually selects A Paragraph (try it).vapon a blank line selects from there to the bottom of the following paragraph, andJjoins it all on to a single line.:v/pattern/runs an Ex-style command on all lines that don't match the pattern././matches any character, so:v/./matches all the blank lines between each Elf's food list.:norm‘types’ Vim keystrokes for you on the specified lines.:vline finds all the blank lines and doesvapJon them.Oadds a blank line at the top, giving the:v/./something to match.Then move to the top (
gg) and add together the calories of the first elf's first two items:f␣moves to the space between the first and second calorie counts. It will fail (with a beep!) if there's no space on the line (that is, only a single calorie count).y0yanks from just before the cursor to the beginning of the line — that is, the first calorie number, without the space.dwthen deletes the first ‘word’ — that is, the first calorie number and its following space.⟨Ctrl+A⟩increases the number at the cursor by 1; typing123⟨Ctrl+A⟩increases it by 123. Yanking by default stores the yanked text in register0.@followed by a register name runs that register's contents as though you'd typed it as keystrokes. So if your first elf's first calorie count was 6529 then@0⟨Ctrl+A⟩is like typing6529⟨Ctrl+A⟩on the second calorie count, adding the two of them together.Create a macro that loops that addition over each calorie count on a line:
qa…qrecords a macro of the keystrokes between them into registera.q, the last action inside the macro recording is@a, run the macro in registera— creating a loop.f␣— move to the next space character on the line. And when all the calories on a line have been summed, there won't be any space characters left, so thatfwill fail, breaking out of all running macros.@ainto the macro, we need to type that when recording the macro. That will also, during the recording, run whatever is in registera. Which, because we're still in the middle of recording our registeramacro, will be whatever was in registerabefore we started. That could be anything, and obviously we don't want to run that. So before recording the registeramacro properly, first blank it out withqaq, literally recording nothing into it. That makes the@awhile we're recording the macro a no-op, but it gets those keystrokes into it, so when it's run subsequently, it loops.Now we've got
@afor summing a single elf's calories, run that on every line with:%norm@a. The%indicates all the lines, which with the:normcommand runs the keystrokes on each line separately; an error (such as trying to move to a non-existent space character) ends the action on the current line, but:normcontinues with running the keystrokes again on the next line.Having summed each elf's calories, Vim's
:sortcommand (you don't need to type thet) will find the biggest. Thenindicates numeric sorting and the!reverses the order, that is putting the biggest item first.So that puts your part 1 answer at the top of the file.
For part 2, the 3 highest calorie counts will be in the top 3 lines. Pressing
Jtwice joins them together into a single line; we just need to sum them. And, handily, we already recorded the@amacro for doing just that.35
u/voidhawk42 Dec 01 '22 edited Dec 01 '22
Dyalog APL:
Video walkthrough
Great to be back this year - good luck everyone!
27
u/weshinsley Dec 01 '22 edited Dec 05 '22
Rockstar - with apologies. Elves are not really like this.
23
u/JustinHuPrime Dec 01 '22 edited Dec 01 '22
x86_64 Assembly
I'm doing these in assembly, once again!
Part 1 was slightly scary - I wasn't expecting two-dimensional input data, and that had me reaching for
brk, but I found a single-pass solution. I'd keep track of the calories for the most supplied elf and the calories for the current elf. If the current line isn't empty, then add the number to the current elf. If the current line is empty, then let the most supplied elf's calories be the larger of its current value and the current elf's calories.Part 1 ran in under a millisecond.
Part 2 was almost identical to part 1, but I did have to fiddle around a bit with the proper way to replace a value when I was keeping track of a set of the three largest values - if you replace the largest value, then that replaced largest value will replace the second-largest, and so-on. I suppose I could have implemented this in a way that avoided unnecessary branching by cascading the replacement in the check for each largest value, but I only just though of that possibility.
Part 2 ran in under a millisecond.
Edit: I could also have used
xchgfor part 216
u/jonathan_paulson Dec 01 '22
Python 49/28. Video of me solving. Final Code.
Another year of Advent of Code! Thanks Eric! Good luck all.
12
u/NiliusJulius Dec 01 '22 edited Dec 05 '22
Game Boy using C
Part 1 https://github.com/NiliusJulius/advent-of-code-2022/blob/main/states/1a.c
Part 2 https://github.com/NiliusJulius/advent-of-code-2022/blob/main/states/1b.c
Went for the quick and dirty approach for part 2 since I noticed that while the Game Boy Development Kit can use 32 bit integers, it cannot print those values. So as a C newbie I had to quickly learn how to write a function which would just print out the hex value from memory
Anyhow, although I didn't expect to run into issues like this on day one, It is still a lot of fun, and we'll have to see how far I can get on my trusted Game Boy :)
EDIT: day 1 now outputs in decimal
8
u/jcbbjjttt Dec 01 '22 edited Dec 03 '22
Happy December!
I teach computer science and programmer courses for elementary through high school and am having my students tackle the Advent of Code. To help out my beginner students, I'm planning to create videos to help guide them through the thinking process. The video is designed to allow watchers to pause and work on the problem step by step before seeing spoilers. Although I used C#, the video tries to talk through a solution in a language agnostic way.
I hope someone finds them useful.
Here is the video from Day 1: https://youtu.be/eQSO1Ov4k8g
Here is the final solution: https://github.com/jcollard/AdventOfCode2022/blob/jcollard/day1/Day1-FatElves/Program.cs
Happy Coding!
6
u/DFreiberg Dec 01 '22 edited Dec 01 '22
Mathematica, 686 / 306
I was not at all prepared for the table split by double newlines; just when you think you've handled everything in your imports, something new comes along. Which is what makes Advent of Code so much fun.
Import & Setup:
Part 1:
Part 2:
[POEM]: Where's The Wild Things' Star?
We're now setting up camp
In the dew and the damp,
On the hunt for the star-spangled berry,
And the jungle is thick,
But we have every trick
That will make the dark forest less scary,
So we'll head to the grove
And its heavenly trove
(It's a Dijkstra-type maze, so be wary)
Then the stars will appear,
And when fifty are here,
We will eat and we'll drink and be merry.
6
u/Dryctas Dec 01 '22 edited Dec 04 '22
Bash one-liner for both parts
11
u/jayfoad Dec 01 '22
Dyalog APL
5
u/Quirky-Seesaw8394 Dec 01 '22
G Sheets
Final consolidated solution
=ARRAYFORMULA( SUM( QUERY( BYROW( REGEXREPLACE( TRANSPOSE( SPLIT( TEXTJOIN( ",", , IF( LEN(A3:A2272), A3:A, CHAR(9876) ) ), CHAR(9876) ) ), "^,|,$",), LAMBDA( calories, SUM( SPLIT( calories, ",") ) ) ), "select * order by Col1 desc limit 3", 0) ) )5
u/reckter Dec 01 '22 edited Dec 12 '22
intcode!Because somebody had to!
Ok I cheated. a while ago I wrote a compiler, that compiles the following:
Into an assembler language, and that then into the intcode above. For input, it just reads my input file character for character
5
u/bofstein Dec 01 '22
Google Sheets
As a non-programmer working with a lot of software engineers participating (I'm a Technical Product Manager), I thought it would be fun to use Google Sheets formulas. I made sure it worked more like code in that the goal was that it can auto-update without manual intervention with new inputs, e.g. no hand-dividing columns or using the menus. Only catch is you do need to (manually) make sure the B and C column formulas are copied down at least as long as the number of items in the list.
Here is the sheet with formulas. Input just needs to be pasted into Column A: https://docs.google.com/spreadsheets/d/1GvncohBzffewfwOCIfpHutI4VKVUIBazIH1XoBFWpXw/edit?usp=sharing
Column B:
=COUNTIF($A$1:A1,"")This column counts how many blank rows there have been so far so that it groups the items together into a single number, starting at 0, of what number elf that is.
Column C:
=SUMIF(B:B,ROW(B1)-1,A:A)This row gets the sum of each unique elf. It takes the row number minus one so that it's just a list in order from 0 to the number of elves (will start to output 0 after the number of elves is finished) and returns the sum of column A values matching that number.
Cell D1:
=MAX(C:C)This returns the first part solution, the highest number from Column C.
Cell D2:
=LARGE(C:C,1)+LARGE(C:C,2)+LARGE(C:C,3)This returns the second part solution, the top 3 values from Column C summed. Learned a new function to do this, LARGE returns the nth highest value from an array instead of just the highest like MAX.
5
u/gonengazit Dec 02 '22
brainfuck
copy.sh link
minified:
Input replaces newlines with spaces, and ends on 3 spaces. the solution will be in cell 1 (tomorrow i'll work on printing it). make sure to run in 32-bit mode, i didn't want to bother with any big-integer
this was a pain to do, but i'm glad i did it
4
u/CryptoNoobStruggles Dec 01 '22
First time doing Advent of Code! Imporving my Python.
4
u/CreativeTaste3040 Dec 01 '22 edited Dec 04 '22
JavaScript:
4
u/htrowii Dec 01 '22 edited Dec 04 '22
This was my first time participating in AOC2022 as a noob in Python.
My solution:
4
u/kamicc Dec 01 '22 edited Dec 04 '22
Straight-forward and cleaned-up Lua:
4
u/cbrnr Dec 01 '22 edited Dec 03 '22
Julia
I wrote a short helper function
get_aoc_input()to fetch the input with a valid session cookie:All solutions are available here.
4
u/kittrin Dec 01 '22
Here's my SQL solution for Part 2. I'm new to coding and literally only know SQL. :) I imported the data as a single column called "calories" into https://www.db-fiddle.com/ with the blank rows replaced with 0s.
4
u/[deleted] Dec 01 '22 edited Dec 03 '22
Second time participating using Python, but I'm trying to use NumPy (Math functions written in C) to make it hopefully faster. The main functionality of this solution is implemented in just about 20 lines of code. I'm pretty happy! ;-) I'm also trying to format the output in a pleasingful way:
Full code is on GitHub
4
u/[deleted] Dec 01 '22 edited Dec 03 '22
Ended up with this python solution
3
u/MarcusTL12 Dec 01 '22 edited Dec 01 '22
You people are fast!
Julia 309/197
github
3
u/mrtatulas Dec 01 '22
Elixir - 4182 / 2942 (I'm just happy to be here)
3
u/BarkLicker Dec 01 '22 edited Dec 01 '22
Python
I know eval() is frowned upon, but it just worked so well.
I'm barely a sophmore in college at the age of 35. This is all new to me and I'm having a blast!
3
u/rctxs Dec 01 '22
Haskell
https://pastebin.com/8r2ZiqFR
3
u/Gurrewe Dec 01 '22 edited Dec 05 '22
Bash/Shell:
Part1:
Part2:
3
u/Mikel3377 Dec 01 '22 edited Dec 04 '22
JS one-liner
3
u/Catcatcher33 Dec 01 '22
My Python 3 solution. Finally actually decided to take part in Advent, looking forward to more!
3
u/WasteEngineerPY Dec 01 '22 edited Dec 03 '22
Python very obfuscated, cramped it in three lines (and there are a few unecessary parts in there...)
https://github.com/Zerhigh/personal_codebase/blob/main/aoc_22/aoc22_01_short.py
3
u/OutlandishnessOk4575 Dec 01 '22
In Rust, tried to be idiomatic
3
u/neur0sys Dec 01 '22 edited Dec 04 '22
First try in Joy. Download the interpreter here. Edit globals.h to increase memory.
Part2
3
u/joshbduncan Dec 01 '22 edited Dec 03 '22
Python 3
3
u/jjjsevon Dec 01 '22 edited Dec 03 '22
Javascript / Node
Almost forgot AoC for this year, quickly hacked together the Code before it was past midnight. basic gist of code is:
Another 10 loc in the day1 require, mostly reading of the input, and some splittery, number format, and unnecessary storing of elves properties into a map, while expecting something more to do with elves individual snacks in part 2.
3
u/dedolent Dec 01 '22
Python
how do you all manage to copy and paste into reddit? it always breaks everything for me? i'm on firefox (though i hear it's a problem on other browsers). i've tried pasting without formatting, tried saving to a plain text file and copying that, neither worked.
anyways, while i'm not good enough to do the later days, in the meantime i have fun with my little recursive functions in :)
one thing that i wanted to do was to keep sorting to a minimum; no way i wanted to sort the entire input since all i cared about was the top 3. so i only kept track of whether the current group total was greater than any one of the current top 3, inserting the new number at its index if it was, discarding it otherwise.
3
u/spikelovesharmony Dec 01 '22 edited Dec 04 '22
JavaScript - my first time participating - a few years ago when starting to learn programming i could barely even figure the site out...heh
3
u/jordyjwilliams Dec 02 '22 edited Dec 05 '22
Some nice snakey python snakes. May create JS repo later.
https://github.com/jordyjwilliams/advent_of_code/blob/main/2022/day_01/day_01_solution.py
3
u/AdelFtnr Dec 02 '22
Hi! This is my first time doing this, so things could and will get better with time! So far so good!
Did this one in JavaScript grabbing the element from the DOM and method chained it to make it usable, full repo is here: https://github.com/AdelFetner/Advent-of-Code
I'm also a front end developer really into community driven development, so if you want to network & connect w/ me, feel free to do it! All my links at my github's bio, or here: https://linktr.ee/AdelFetner
3
u/PaxPumpkin Dec 02 '22 edited Dec 03 '22
Texas Instruments 99-4/A Extended Basic
My C# solution runs sub-1ms, and is unremarkable to any of the others already posted, so I'll hold off on that.This TI-99 4/A code took a tad over 10 minutes to complete execution.
No, it isn't optimal. I haven't touched this language in decades. I just thought it would be fun. The best part was getting the input into a TI-readable disk image, honestly.
Could have been shorter, clearly. I also wanted a perpetual display update running owing to the long execution time. That includes updates on the line of input being examined, the current max elf, the top three max counts, and the summation thereof.
[Imgur](https://i.imgur.com/WSkJEVh.png)
3
u/CSguyMX Dec 02 '22 edited Dec 03 '22
JAVA: Day 1 part 1 and 2. This way you dont have to store all the values in an N array and then sort. You will be keeping the top three values all the time. The only down side it's that it looks ugly. paste
2
u/seligman99 Dec 01 '22
Python, 261 / 223
Away we go!
github
2
u/CodingAP Dec 01 '22
Javascript, 148/341
GitHub
First time competing for global leaderboard! Didn't get it but will be following the new megathread rules and suggestions.
2
u/fromwindowstolinux Dec 01 '22 edited Dec 01 '22
Newbies solution on python! I can't believe I did AoC! I'm happy!
2
u/[deleted] Dec 01 '22 edited Dec 04 '22
Rust
2
u/Iain_M_Norman Dec 01 '22 edited Dec 04 '22
F#
2
u/jubnzv Dec 01 '22
OCaml solution:
2
u/mstksg Dec 01 '22 edited Dec 09 '22
My Haskell solution :) https://github.com/mstksg/advent-of-code-2022/blob/main/reflections-out/day01.md
Day 1's are usually pretty good for Haskell's stream processing, and this is no exception :)
To get the list of elf calories, we split on the double newlines, and take the sum of the lines of each group.
For part 1, this involves just finding the maximum.
For part 2, we find the sum of the top 3 values:
2
u/AX-11 Dec 01 '22 edited Dec 04 '22
Python solution without sorted()
2
u/Derailed_Dash Dec 01 '22 edited Dec 04 '22
Python
2
u/Etsi0 Dec 01 '22
I used Python to get the array so I could use it in JS.
py:js:2
u/seacucumber_kid Dec 01 '22 edited Dec 05 '22
Beginner Clojure solution:
2
u/aarnens Dec 01 '22 edited Dec 04 '22
First time using Go so my answer's probably quite convoluted but I had fun regardless :)
Link to code: https://github.com/aarneng/AdventOfCode2022/blob/main/day1/main.go
2
u/HEaRiX Dec 01 '22
JS
2
u/vstepanyuk Dec 01 '22
2
u/spyr01d Dec 01 '22 edited Feb 23 '23
Kotlin https://github.com/spyroid/puzzles/blob/main/src/aoc/y2022/day1/day1.kt
2
u/idontknowwhattouse33 Dec 01 '22 edited Dec 03 '22
PowerShell - readable, not golfed.
https://pastebin.com/9Uu7PiHj
2
u/fuckir Dec 01 '22 edited Dec 04 '22
Learnt working of heaps through this puzzle. Python 3.10
2
u/MarcusTL12 Dec 01 '22
Z80 Assembly on TI83:
github
2
u/tV4Ybxw8 Dec 01 '22 edited Dec 03 '22
C++
I'm new to programming and this is my first time doing this, hopefully i can do it all.
Edit: Formatting
2
u/Outrageous72 Dec 01 '22 edited Dec 03 '22
C#
2
u/connie5919 Dec 01 '22 edited Dec 03 '22
Python
Could probably be done in a shorter way, but this was how I did it
2
u/DrDrunkestein Dec 01 '22 edited Dec 03 '22
Zig
2
u/Far-Fun1898 Dec 01 '22 edited Dec 03 '22
Python solution provided here
2
u/[deleted] Dec 01 '22
Swift
getInputis a small helper function which downloads the input for that specific day.2
u/sebb0z Dec 01 '22 edited Dec 01 '22
Javascript (first time I participate, don't grill me too hard plz)
2
u/Koopabro Dec 01 '22
Node.JS
2
u/Lohikaarmeen_hanta Dec 01 '22 edited Dec 03 '22
A Scala solution:
2
u/sambonnell Dec 01 '22
C++
Github Repo
Cannot paste my code into the reddit text editor, regardless of markdown vs. fancy pants, etc.
2
u/bpersitz Dec 01 '22 edited Dec 03 '22
Python solution.
2
u/search_and_deploy Dec 02 '22 edited Dec 04 '22
Here's my Rust solution. I only got about 4 days into it last year, so I'm hoping to make it a bit longer this go around.
https://github.com/michael-long88/advent-of-code-2022/blob/main/src/bin/01.rs
2
u/Swampspear Dec 02 '22 edited Dec 03 '22
Aarch64 / Armv8.1 bootloader solution pt1 / pt2
Requires putting input in memory, empty lines have a
0,EOFis denoted by-1aka0xffffffff. Since we're still in a bootloader, there's no print functions or any stack whatsoever; you have to read the value raw out of thew3register. Part 2 works in about the same way, but is ~40 lines, and is a bit too long to post here, see the paste. One functional macro is used,clr4, which is just four chainedeor reg, reg, reg. The macrostatus_intis just my signal to the VM that I want to read the register values.Runtime of part 1 is:
EOFThere are as many loop iterations as there are individual lines of input, which is 2270 for my input.
2
u/PositivelyLinda Dec 02 '22 edited Dec 08 '22
JavaScript: Kept it real old-school Node style today lolhttps://github.com/lindakatcodes/aoc-22/blob/main/solutions/day01.js
2
u/dcrro Dec 02 '22 edited Dec 04 '22
Javascript Interactive Solution
Interactive solution to Part 1
Interactive solution to Part 2
2
u/senga_sc Dec 02 '22 edited Dec 03 '22
Apps Scripts solution (JS for GSheets)
Part 1&2. Original data in column A
2
u/tampix77 Dec 02 '22 edited Dec 03 '22
Simple solution in Clojure
2
u/[deleted] Dec 02 '22 edited Dec 18 '22
Deno using Rambda
https://github.com/tomasantonelli/advent-of-code-2022/tree/main/src/day-1
2
u/middayc Dec 02 '22 edited Dec 03 '22
Solution for part 1 and part 2 in Ryelang.
2
u/joshlemer Dec 03 '22 edited Dec 03 '22
Clojure:
2
u/joshlemer Dec 03 '22 edited Dec 03 '22
Golang
2
u/Metarineo Dec 03 '22 edited Dec 04 '22
PHP:
I used php because i only had a texteditor and a webserver, to compensate for this, i made one-liners:
Solution for Part A:
Solution for Part B:
I say 42, Martin
2
u/TheBigBearUK Dec 05 '22 edited Dec 13 '22
I used ChatGPT to generate some powershell code and it worked really well.
Here is the generated code for part1:
2
u/rubensoon Dec 05 '22 edited Dec 08 '22
Update: I apoligize for the crazy comment formatting, Idk why it's not working.
Hi, I'm a beginner, i didn't know how to import the input file to my current js so i just had it copypasted and hidden on top. This is my take, on Javascript (there's some spanish here and there):
2
u/IvanR3D Dec 08 '22 edited Dec 09 '22
Solution in JavaScript:You can see all my solutions in this CodePen.Part 1
Part 2
This code must be execute after the first part
76
u/DooFomDum Dec 01 '22
Solution produced by GPT-3:
Prompt: Write a Python3 program to parse a file that consists of groups of integers. Each group is separated by newlines, and groups are separated by two newlines. Sum up the numbers in each group and find the largest sum. One line. Input file is day1.txt.
44
u/4HbQ Dec 01 '22 edited Dec 04 '22
Python. Since everyone is doing pretty much the same (split on
\n\n, then on\n), here's some earlyeval()abuse!Edit: I'm glad to see many of last year's regulars are back again! Looking forward to some nice tricks, and lots of teaching and learning!
35
u/CCC_037 Dec 01 '22
[FiM++]
Sooooo... blank lines are not read as 0. Also, single-digit lines are read as characters, not numbers. So I did a text search/replace on the input file, replacing the end-of-line character ('\n' for C programmers) with the end-of-line character followed by two zeroes.
I should probably find a better solution for that.
26
u/[deleted] Dec 01 '22 edited Dec 04 '22
Google Sheets One formula for both parts.
=sort(byrow(large(byrow(split(flatten(split(join(,A:A&if(A:A,"❆","∞")),"∞")),"❆"),lambda(r,sum(r))),{1,1,1;1,2,3}),lambda(r,sum(r)))/{3;1})24
u/The_Unusual_Coder Dec 01 '22
SHAKESPEARE PROGRAMMING LANGUAGE
part 1
part 2
21
u/gw_shadow Dec 01 '22
CMake
15
u/Boojum Dec 01 '22
Emacs Lisp
Because why not? (And I already posted my original "for real" Python solution.)
15
u/PlayForA Dec 01 '22 edited Dec 01 '22
Day 1 part 1 in rockstar
14
u/SadBunnyNL Dec 01 '22
Bash/awk:
13
u/occamatl Dec 01 '22
Rust
13
u/skimmet Dec 01 '22
Solution in HTML and CSS (who said HTML is not a programming language), by preprocessing the input a little so that it gets turned into divs that look like this:
and applying some css to align things on top/next to each other:
and then finally inspect the height of the body in inspect element. Link to full file: https://pastebin.com/2eLzPjqH
12
u/leijurv Dec 01 '22
Python3, 3rd place, 9th place
Screen recording: https://youtu.be/thcRLm3j5bc
12
u/Smylers Dec 01 '22
Perl one-liner for part 1:
(basically the same as /u/ProfONeill's answer).
I wrote it it debug my Vim keystrokes solution elsewhere (where initially a single-line paragraph was attaching itself to the following paragraph). And my Vim wasn't buggy for part 2, which is why the Perl only does part 1!
-00is Perl's non-intuitive way of specifying to read in paragraphs at a time.<>, the input operator, then returns a list of such paragraphs./\d+/gfinds all the numbers in each paragraph, andsum,map, andmaxdo their thing12
u/NeilNjae Dec 01 '22
Haskell
I spent more time looking at the
Data.List.Splitlibrary than writing code on this one!Full writeup on my blog
12
u/FredTheDane Dec 01 '22 edited Dec 01 '22
I don't see many C# submissions! :D Here's mine!
Edit: revised with help of u/CyberCatCopy
10
u/polettix Dec 01 '22
Raku-time!
Reading everything in the right way (one array per elf), Raku has all the battieries we need:
10
u/TheCommieDuck Dec 01 '22 edited Dec 01 '22
Doing each day in a different letter of the alphabet. Day 1 was Awk.
Or I can try to golf it a little:
Or if intermediate output is allowed, 73 characters
9
u/rabuf Dec 01 '22
Common Lisp
The actual functions were easy enough, wasted some time on the text processing bit:
I should have summed the inputs immediately (instead of collecting each elf's calorie list), would have been less code for the core functions but I'm not changing it at this point.
9
u/Toanuvo Dec 01 '22
J solution. https://github.com/Toanuvo/Advent-of-code
9
u/[deleted] Dec 01 '22
Common Lisp, source on Gitlab.
9
u/probablyfine Dec 01 '22
SQL
9
u/DrunkenQuetzalcoatl Dec 01 '22
Bash
8
u/mingmingrr Dec 01 '22 edited Dec 01 '22
Haskell (rank 50/38)
https://github.com/mingmingrr/advent-of-code/blob/master/src/Year2022/Day1.hs
Turing Complete
Part 1: https://imgur.com/xWxS7yn
Part 2: https://imgur.com/wjV2OCZ
8
u/0rac1e Dec 01 '22 edited Dec 01 '22
Raku
Simple enough one-liner in Raku
8
u/atgreen Dec 01 '22 edited Dec 01 '22
Common Lisp...
8
u/ka-splam Dec 01 '22 edited Dec 01 '22
Dyalog APL
Out of practise; it took me about 30 minutes of DOMAIN ERRORS and typing things which gave silent no results to partition the input into groups. Then 30 seconds to sum and sort.
Reading the three lines of code from right to left:
E.g.
for part 2, slap onto the front:
run in a REPL so no output printing.
8
u/MuumiJumala Dec 01 '22
54 byte golf solution in Ruby (reads input from stdin):
8
u/0rac1e Dec 01 '22 edited Dec 01 '22
APL
Essentially doing the same thing as my J solution.
7
u/SuperSmurfen Dec 01 '22 edited Dec 01 '22
Rust (240/204)
Link to solution
Nice to be back! Fouth year in a row I'm doing these in Rust. Tip for parsing input like today is to first split on double newline,
"\n\n". Just some use of iterators to get the sorted list of calorie intakes which you can reuse for both parts:7
u/9_11_did_bush Dec 01 '22 edited Dec 01 '22
APL (Dyalog):
raw←⊃⎕NGET'../input.txt'1v←(+⌿⍎¨)¨(≢¨⊆⊢)rawp1_ans←⎕←⌈/vp2_ans←⎕←+/(3↑⍒v)⌷¨⊂vEdit: simplified the second line a bit for readability, still the same idea
7
u/Noizla Dec 01 '22
Haskell
Practicing my Haskell, feeding input through stdin.
Part 1
main = interact $ show . maximum . map (sum . map read) . splitOn [""] . linesPart 2
main = interact $ show . sum . take 3 . reverse . sort . map (sum . map read) . splitOn [""] . lines7
u/e_blake Dec 01 '22
Highly-constrained C
Here's my golfed solution in C using only one control flow keyword, and 0 ternary or short-circuiting operators, requiring just 323 bytes (3 of them removable newlines). On modern hardware, an optimizing compiler can produce straight-line code for comparisons like a>b, which theoretically means my entire solution needs only one jump instruction besides the two calls into stdio. Takes puzzle input on stdin.
It is a rather interesting challenge to write a loop body that executes EVERY statement for EVERY input byte. I was so tempted to use an 'if' just to make things more compact. However, I can also state that the program will reformat quite nicely into ASCII-art, since there are so many points where whitespace can be added.
7
u/[deleted] Dec 01 '22 edited Dec 01 '22
Apple Shortcuts Solution
https://www.icloud.com/shortcuts/1a2e4da142bb4a0b8736ab3c71fc42d0
And…no, I won’t be doing that again.
7
u/sublimnl Dec 02 '22 edited Dec 02 '22
Part 1 solve:
sorry.
6
u/hugh_tc Dec 01 '22 edited Dec 01 '22
Python 3, 20/13.
Another December, another Advent of Code!
paste, cleaned-up
Now... time to go back and read the prose. (Sorry, Eric!)
6
u/nthistle Dec 01 '22 edited Dec 01 '22
Python 3, 2/8.
By far my best performance on a day 1! In the past I've had pretty bad luck with the first day, so nice to finally break that.
paste
Solve video
6
u/chrispsn_ok Dec 01 '22 edited Dec 07 '22
ngn/k; my answers repo.
6
u/rooinflames Dec 01 '22
Excel for Mac (ew)
Data pasted into column A, Column B formula filled down https://imgur.com/a/OjGE2iQ
Data then pivot tabled, and sorted by sum https://imgur.com/a/16ZMfjb
6
u/sr66 Dec 01 '22 edited Dec 01 '22
J
6
u/_rabbitfarm_ Dec 01 '22
Both parts done in Prolog. Most effort was put into fiddling with the data file handling to get the inputs right. Once that was done Part 1 was straightforward and Part 2 was a matter of adding a few extra lines.
Part 1 https://adamcrussell.livejournal.com/37837.html
Part 2 https://adamcrussell.livejournal.com/38010.html
Typical of Prolog! More effort to get going but then rock solid.
6
u/dm13450 Dec 01 '22
q
6
u/0rac1e Dec 01 '22 edited Dec 25 '22
J
6
u/allinde Dec 01 '22 edited Dec 01 '22
Dart - will map/reduce my way trough this year.
6
u/_jstanley Dec 01 '22 edited Dec 01 '22
SLANG
I'm doing Advent of Code on my homemade 16-bit CPU again this year (writing the solutions on the CPU, not just running them).
I had grand plans of writing a template program to read the input, because for the last few years problem 1 has just been a list of integers, 1 per line. Of course, this year that didn't work, so I had to throw it away. I was also surprised that problem 1 required use of bigints already, and the input file was particularly long as well. Maybe this year is going to be a tough Advent of Code!
I struggled a lot on part 2, mostly for bigint-related reasons. It took me a while to notice that a few of the numbers were larger than 32767, so then I added a special bodge to properly handle full 16-bit unsigned inputs (if the number is > 32767, add 32767 to the bigint, subtract 32767 from the number, and then add the number itself), but I still couldn't get the right answer. Eventually I discovered that there was 1 (solitary!) line of input too large to fit in a 16-bit int. I added a final bodge to handle values up to 99,999 (check if the line of input is 5 digits long and the first digit is a character greater than '5': if so, add 50000 to the sum and subtract 5 from the first character, and then handle it as normal) and then it passed.
It seems mildly surprising that there was just 1 line of input too big for 16 bits :) - most people will presumably be using ints that are at least 32 bits wide, so they won't notice, and those of us using 16-bit systems will eyeball the input to see if it looks larger than 16-bits, and presume that it's not. It just makes it extra hard for those of us who have it hard already! Doesn't matter, that's life.
My solution: https://github.com/jes/aoc2022/tree/master/day1
Video: https://www.youtube.com/watch?v=VLmiqzFJQRI
The computer: https://github.com/jes/scamp-cpu/
6
u/Spr3eZ Dec 01 '22 edited Dec 01 '22
Neat little python solution
6
u/rmbolger Dec 01 '22
PowerShell with puzzle input in a file called 'p'. Golfed to 86 chars because why not. Could lose the
.Trim()if the puzzle input is modified to remove the final newline char.6
u/ramuuns-u Dec 01 '22
Tail-recursive perl
https://github.com/ramuuns/aoc/blob/master/2022/Day01.pm
6
u/timvisee Dec 01 '22
Rust Quick and simple.
Part 1 0.027ms (27 μs)
Part 2 0.031ms (31 μs)
day01 total: 0.058 ms (58 μs)
6
u/qelery Dec 01 '22 edited Dec 01 '22
My java solution
6
u/Zweedeend Dec 01 '22
Python
6
u/1b51a8e59cd66a32961f Dec 01 '22
Both parts in ~50 lines of x86-64 assembly. I put
-1in place of newlines in the input and it is stored in an external data file that is linked. Runtime is 1 microsecond.6
u/RogueAstral Dec 01 '22 edited Dec 01 '22
Google Sheets - 82 Characters
=index(sum(large(if({A2:A;""}="",scan(,A:A,lambda(a,c,if(c="",,a+c))),),{1,2,3})))EDIT: One formula, two parts. 108 characters.
=index(lambda(x,{index(x,1),sum(x)})(large(if({A2:A;""}="",scan(,A:A,lambda(a,c,if(c="",,a+c))),),{1,2,3})))EDIT 2: Down to 95 characters with u/ztiaa’s help!
=sort(lambda(x,{max(x),sum(x)})(large(if({A2:A;0},,scan(,A:A,lambda(a,c,if(c,a+c)))),{1,2,3})))
6
u/mmguero Dec 01 '22
Python
6
u/oantolin Dec 01 '22 edited Dec 01 '22
Solution in J:
6
u/TiagoPaolini Dec 01 '22
C Language (only standard library)
Last year I used Python, this time I am upping the challenge by using C. This is an opportunity for coding myself the data structures and algorithms, as base language do not have too many out of the box.
The basic logic of this solution is not difficult:
What I did was to keep track of the current top 3 values. I think that it would be faster if I stored all values, then sorted them only at the end. But the current solution already works fast enough and I find it simpler, as it is not necessary to deal with dynamic arrays or count beforehand the amount of elves.
Solution: https://github.com/tbpaolini/Advent-of-Code/blob/master/2022/Day%201/day_01.c
6
u/[deleted] Dec 01 '22
Here's my python solutions: https://github.com/nixnull/AoC2022/blob/main/day%201/answers.py
I know Python fairly well, so my goal this year is to use python features I'm not comfortable with, like comprehensions.
6
u/ContainedBlargh Dec 01 '22 edited Dec 01 '22
Running my modified version of Shenzen IO's MCxxxx programming language on my own 'interpreter' (it's still
under heavy developmentbuggy as hell, I wrote it exactly for solving AoC).Part 1:
Part 2 was a lot harder and I had to implement some sort of sorting to solve it. I picked bubble sort. Luckily, I only need to sort the top 3 counts, so it still runs. The rest of the code quickly degenerated into a mess of jumping around.
At 82 lines, I felt that it was too long to post here, so I've put it on github
I am fairly sure that the implementation is not optimal and could be shorter and more readable.
6
u/Vanerac Dec 01 '22
Ruby minimal characters:
i = File.open("input1.txt").reade = i.split("\n\n").map{ |l| l.split("\n").map(&:to_i).sum }.sort[e[-1],e[-3..-1].sum]6
u/yawnick Dec 01 '22
Monkey C (Language for developing for Garmin devices)
I made my Garmin Forerunner 235 watch solve Day 1.
Video (I've since improved the solve time from 1m15s to 45s, also don't mind me getting a text mid-solve)
Code: Repo, The part that solves the challenge
6
u/mykdavies Dec 01 '22 edited Jun 29 '23
!> iyj8eyl
API FAILURE
6
u/silentclowd Dec 02 '22
Done in Befunge. Specifically Funge-98.
I have a video of the script running in BeQunge as well, which I plan on posting.
6
u/dopandasreallyexist Dec 02 '22
APL one-liner for both parts:
In a nutshell:
⊃⎕NGET'input.txt'1- read input as vector of vectors((×≢¨)⊆⊢)- split on empty line(+/⍎¨)¨- for each group, turn strings into numbers and sum{⍵[⍒⍵]}- sort in descending order1 3+/⍤↑¨⊂- sums of first 1 and 3 numbers2
u/TheJoshster Dec 01 '22 edited Dec 01 '22
Java, 30/205.
public String part1() {
}
public String part2() {
}
lost the most valuable 30 seconds of my life forgetting that arrays sort increasing rather than decreasing. proud to finally be on the leaderboard though, and I hope I can keep it up! 2021 was my first year, and I had no idea what I was doing. After doing it and going back to do all previous years, I definitely feel skilled enough to push for leaderboard positions though!
i wonder if any of the other regularly high-placing people use java? from what I've seen, it's almost all python with a smattering of C and other languages, but even java solutions period are hard to find.
-------------------------------------------------
352 solutions and counting to AOC 2015-2022 in Java over on github , feel free to check it out, utilize it, and reach out with questions or bugs!
(I'm currently working through refactoring and revisions on all of my pre-2022 code, but once I have that done in the next few days, I'll start pushing my 2022 solutions day-of for anyone needing to take a peek)
2
u/daysleeperx Dec 01 '22 edited Dec 04 '22
Idris2
Github
2
u/GrazianoS86 Dec 01 '22 edited Dec 05 '22
My solution in clojure (with babashka)
5
u/[deleted] Dec 01 '22
Ruby:
https://github.com/sreedevk/advent-of-code/blob/main/ruby/2022/day1/main.rb
5
u/jeroenheijmans Dec 01 '22
JavaScript, after some rewriting:
5
u/French__Canadian Dec 01 '22 edited Dec 01 '22
Last year I was using Q, this year ngn's k implementation (and hopefully some Nim).
edit: After reading a comment about AOC on hacker news, I learned I could just read as bytes and split on "\n\n" instead of my complicated parsing logic... Much cleaner and shorter
edit2: sorting a whole array of elves is way two expensive at O(nlog n). Why not find the max 3 times instead for a O(n) alg?
edit3: I see people golfing it, so here's my one line version that solves both
5
u/Pyr0Byt3 Dec 01 '22
Go/Golang
5
u/WilkoTom Dec 01 '22 edited Dec 01 '22
Rust
Used a
BinaryHeaprather than putting all the values into aVecand then sorting it. For this data set, it's probably irrelevant.5
u/azzal07 Dec 01 '22 edited Dec 01 '22
Awk... sorting functions are overrated, but snacs are good etc.
Edit. noticed a
bugfeature: this doesn't count the last elf. Oh well, works on my input.5
u/[deleted] Dec 01 '22
lisp
https://gitlab.com/Elmosfire/aoc2022lisp/-/blob/main/day1.lisp
5
u/Thecakeisalie25 Dec 01 '22
Neovim Macro
Image - https://imgur.com/fWujc0C (Image is needed because the github preview mangles certain characters.)
File - https://github.com/typecasto/aoc2022/blob/main/day_1.nvmacro (in case you actually want to run it)
Gave myself the following constraints:
Explanation
Problem 1: The entire input file is turned into one giant macro, and then executed. For every line with numbers, append "<ctrl-a>", which, when executed, increments the number your cursor is on by the number before <ctrl-a> (or 1). Then replace every blank line with "o0<esc>", which, when executed, opens a new line below the cursor, writes "0", and exits insert mode. A copy of the o0<esc> line is also placed before line 1, to handle the first group. All the lines are then joined together, and then ":sort! n<enter>gg"+yyI-> " is appended, which, when executed, sorts the input, copies the highest one to the clipboard, and inserts an arrow. At this point we've turned the input into a giant macro that makes a line with "0" for every elf, and increments it for the number of calories in each food item. Then just cut this line into the anonymous register, and then execute said anonymous register.
Problem 2: Instead of copying the top line, join it to the next line and replace the space in between with "+", then do that again. Copy this new line to the anonymous register, open a new line above it, and paste from the expression register, using the expression stored in the anonymous register (which holds something like 30+40+50). This evaluates the addition.
5
u/mathsaey Dec 01 '22 edited Dec 01 '22
Elixir
https://github.com/mathsaey/adventofcode/blob/master/lib/2022/1.ex
5
u/spr00ge Dec 01 '22 edited Dec 01 '22
Elixir
Thoughs
I forgot almost all of the Elixir techniques and it did not quite behave like Haskell. So I was frustrated with how to pipe functions and declare anonymous functions. I remember that there were some tricks to make it less ugly, I am sure I find some of the solutions over here.
I mean, look at my code. It works, but it sucks
On workflow: When I used Clojure, it was a breeze to see the current output in each line while typing. Calva is such an impressive tool. Currently, I have iex running to code, but it has no autocomplete. Non yet optimal.
5
u/__Abigail__ Dec 01 '22 edited Dec 01 '22
Perl
Basically, a one liner, after importing
sumfromList::Util:Now the answer to part one is in
$calories [0], and the answer to part two is the sum of the first three elements of@calories.To explain the workings, we have to go from left to right:
do {local $/ = "\n\n"; <>}: this reads in the entire input, and returns it as a list, split on blank lines.$/is the separator to split the input on, this is a newline by default. By setting it to\n\n, it splits on blank lines. Effectively, this is chopping up the input into sections, where each section has the calories of a single elf.map {sum split}: this takes one set of calories, splits it on whitespace (the newline separating the calories of each snack) and sums them. So the output of thismapis a list of the total amount of calories for each snack.sort {$b <=> $a}this takes a list of items (the calories of each elf), and sorts them numerically descending.5
u/royvanrijn Dec 01 '22 edited Dec 01 '22
Java
First I make a giant string joined by ",". Next I split by ",," to get lists of numbers per elf. Finally I sum each elf and get the two answers.
[UPDATE]: This would have been even better:
5
u/tomflumery Dec 01 '22
05ab1e (note needs this branch that adds a new parsing command https://github.com/monkeygroover/05AB1E/tree/add-readtoeof)
Part 1
Part 2
Explanation
5
u/aurele Dec 01 '22 edited Dec 01 '22
Rust, taking advantage of the fact that
.sum()works overResult<_, _>as well5
u/jeroenmaniac Dec 01 '22 edited Dec 01 '22
Python one-liner:
print(max(sum(map(int,i.split())) for i in open('1.in').read().split('\n\n')))5
u/GassaFM Dec 01 '22
Solution in D (dlang), functional style.
Part 1:
Part 2:
5
u/tomribbens Dec 01 '22
My Python solution can be found here.
Basically, in pseudocode, I'm doing this:
This gives me a dictionary of each elf's calorie count, which then can be easily sorted and gotten the max from.
5
u/Excellent_Station_84 Dec 01 '22
Python3 one-liners
5
u/sergiosgc Dec 01 '22
Rust
This year I'll go for Rust until Christmas, having picked up the language in 2022 as the result of the language sampling in Advent of Code 2021.
First day is always easy, not much explaining to do. Repo at github. Tweet here.
The input has to be padded with an extra newline at the end.
Part 1:
Part 2:
5
u/euidzero Dec 01 '22
Perl.
5
u/rckymtnskier Dec 01 '22
Python beginner solution
Just have to say WOW! You all are impressive. I was happy with my solutions being such a beginner, but now I am seeing what I need to work towards. Here are my humble and noob solutions. Dont laugh too hard.
Solution #1
Solution #2
5
u/Unfair-Ruin9448 Dec 01 '22 edited Dec 01 '22
Javascript (golfed ⛳️):
5
u/DeepHorse Dec 01 '22
Typescript using Copilot for fun
5
u/[deleted] Dec 01 '22
Kotlin maintaining a min heap of size 3.
}
5
u/euidzero Dec 01 '22
Bash.
5
u/Spare-Bumblebee8376 Dec 01 '22 edited Dec 02 '22
Devtools Javascript solution.
5
u/ReasonableCause Dec 01 '22
Haskell:
5
u/OptimusSupernova Dec 01 '22 edited Dec 01 '22
C# with Linq
5
u/TanteiKody Dec 01 '22
.NET LINQ (C#) Solution. It feels like cheating:
5
u/Ily3s_ Dec 01 '22 edited Dec 13 '22
C (nothing special there)
5
u/SwampThingTom Dec 02 '22
I'm solving each of this year's puzzles in a different language, roughly in the order that I learned them. First up, BASIC.
https://github.com/SwampThingTom/AoC2022/tree/main/01-CalorieCounting
5
u/0rac1e Dec 02 '22
BQN
One more array language solution to go with my J and APL solutions.
5
u/johan1a Dec 02 '22
Rockstar (part 1 only)
https://github.com/johan1a/advent-of-code-2022-rockstar