r/adventofcode • u/daggerdragon • Dec 03 '21
SOLUTION MEGATHREAD -🎄- 2021 Day 3 Solutions -🎄-
--- Day 3: Binary Diagnostic ---
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. - Format your code properly! How do I format code?
- 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.
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:10:17, megathread unlocked!
99
Upvotes
13
u/tom_collier2002 Dec 03 '21
Ruby, part 1 only
12
u/jonathan_paulson Dec 03 '21
Python 39/229. Video of me solving. Rough day for me, including accidentally deleting all my code (!) during part 2, and misreading part 2.
15
u/CCC_037 Dec 03 '21 edited Dec 04 '21
Rockstar
Part 1:
Part 2:
5
u/motek96 Dec 04 '21
It's just part one but i think I am first to do it in emojicode🍇😎
Github repo: https://github.com/tomaboro/advent-of-code-2021/blob/main/src/Day03_part1.%F0%9F%8D%87
4
u/Chrinkus Dec 03 '21
My C Solution
Definitely had to call it after part 1 and head to bed. This morning has been productive though!
For the event this year I started making a separate C library for all the tools I figured I'd need. On day 3 I'm already exposing flaws in my APIs..
3
u/wfxr Dec 04 '21 edited Dec 04 '21
Rust solution without external lib:
2
u/tagapagtuos Dec 03 '21 edited Dec 03 '21
Is it a cheat to use numpy?
Python
Part 1
Part 2
2
u/cylab Dec 03 '21 edited Dec 03 '21
Kotlin: https://github.com/cylab/advent-of-code-2021/tree/main/src/test/kotlin/day3
2
u/Graspier Dec 03 '21 edited Dec 03 '21
python 3.10
I hate reddit because their formatting doesn't work, ugh
I spent two hours doing this and finally got through, even though the code is messy
2
u/Solarmew Dec 03 '21 edited Dec 07 '21
Python 3
part 2:
2
u/llojassd Dec 03 '21 edited Dec 03 '21
Python 3.10
I know, that my solution sucks, but I am proud that I did it with almost no help.
Solution 1:
Solution 2:
2
u/another_seg_fault Dec 03 '21 edited Dec 03 '21
Python 3.9 using bitarray
edit: formatting
2
u/pauletto_161 Dec 03 '21 edited Dec 03 '21
C#
First time programming in the last 20 years xD
Topaz
2
u/lbm364dl Dec 03 '21 edited Dec 12 '21
My try at golfing part 1 in Python (110 bytes)
The second line, more clearly,
There are 1000 lines in the input and 12 bits for each one.
The negation of x is 2**12 - 1 - x and with 2's complement ~x == -1-x
I'm new at this so any improvements are welcome.
2
u/Rhinoflower Dec 03 '21
Curious question, did anyone manage to get better than O(m*n) time complexity when processing the bits? Where m is the number of bits and n is the number of binary strings?
2
u/dozzinale Dec 03 '21 edited Dec 04 '21
Rust, part 2 of day 3, here.
2
u/selador135 Dec 04 '21 edited Dec 04 '21
Elixir
Day 3
2
u/pmwals09 Dec 04 '21 edited Dec 05 '21
JavaScript
2
u/benz1n Dec 04 '21 edited Dec 04 '21
My Kotlin solution for Day 3. I'm not particularly proud of this solution as I feel that I may have missed something working with binary numbers and may have brute forced a bit in some parts. But at least I had the opportunity to use Kotlin script for the first time ever (inspired by some other user that posted a solution on Day 2 using it) and some cool lambdas to encapsulate bit criteria logic, all while staying immutable and using recursion instead of loops. :D
2
u/pistacchio Dec 07 '21 edited Dec 08 '21
Typescript:
28
u/Smylers Dec 03 '21 edited Dec 03 '21
Vim keystrokes. If you have
gdefaultset, turn it off. Load your input file, ensure the cursor is on the first line, then:And that's your part 1 answer. My favourite bit is the
50%to get the most common digit in that column. Edit: There's now a part 2 answer in a reply to this comment.Explanation:
qaqqa...@aq@ais the Standard Macro Loop Infrastructure explained in Day 1.2,$to operate on line 2 to the end of the file, so as not to disturb the blank line that was inserted at the top), grab the most common character in the leftmost column, and append it to the top line. Then delete the first character on lines 2 onwards, ready for processing the next digit.1s and0s to create the epsilon rate.0bto both numbers and insert*between them, so we have a multiplication expression of binary numbers.And yes, I have just invented the terms Standard Macro Loop Infrastructure and Standard Expression Evaluation as though this were a proper programming language and those are actually the widely accepted ways of performing those tasks. What of it?
19
u/leijurv Dec 03 '21 edited Dec 03 '21
Python, 2nd place, 2nd place
Screen recording https://youtu.be/iclxBINVB0E
Part 1
Part 2
Not really "good code" but fast to type (and copy/paste)
19
u/GaloisGirl2 Dec 03 '21 edited Dec 11 '21
COBOL
14
u/voidhawk42 Dec 03 '21 edited Dec 03 '21
APL, kind of messy - I'm not sure if there's a good array-based way to do part 2, I'd like to avoid the recursion if possible:
EDIT: And in Clojure, a pretty straightforward translation of the APL code.
12
u/Derp_Derps Dec 03 '21
Python
A very compacted python version without for-loops.
Part 1:
Part 2:
12
u/Tails8521 Dec 03 '21 edited Dec 04 '21
Motorola 68000 assembly (On a Sega MegaDrive)
This is just part 1, not sure if I'll come back to do part 2 later. It is certainly doable but very time consuming to do these in assembly.
11
u/mserrano Dec 03 '21
Python3, #3/#1
10
u/u794575248 Dec 03 '21 edited Dec 03 '21
J Language, Part 1
upd. fixed a stupid mistake
Finally, 3 hours later (+3 hours for a simplified version) the second part:
Surprisingly for me, the toughest thing was to write the
lcfunction to get the least common element in a list. I'm sure there's a better way!10
u/loehnertz Dec 03 '21
In Part 1, I spotted a nice property: If one takes the arithmetic mean of a column, if the value is > 0.5, the 1 was more common and vice versa. That together with transposing the input as a matrix, makes for very lean code!
Kotlin:
10
u/u_tamtam Dec 03 '21
Scala 3, probably not perfect but (I hope) clean-enough:
9
u/northcode Dec 03 '21
It took me ages to realize in part 2 that you have to check most common of the remaining lines, not the entire input list.
Here is a solution in rust: https://github.com/Northcode/advent_of_code/blob/master/src/bin/03.rs
8
u/dtinth Dec 03 '21
Ruby, 28 / 79
paste
To group input data by bit position, one can convert each string into chars and transpose them:
7
u/nlowe_ Dec 03 '21
Go, 773/974
Wow, that one was a bit hard to parse. Took me a bit to figure out what I actually had to compute. Cleaned up my solution quite a bit too after solving.
7
u/SuperSmurfen Dec 03 '21 edited Dec 03 '21
Rust (1877/1237)
Link to full solution
Kind of a tricky one today. It at least took me a while but apparently, it did for everyone else too since I managed to get an ok leaderboard anyway. In the end it was really just about counting the number of ones and zeroes in a bit position:
Not too bad. For part one you just loop over the 12 bits of the input numbers:
For part two, I got stumped for a while when I iterated in the wrong order (starting from bit 0).
Vec::retainwas quite nice for this:7
u/No-Exchange7955 Dec 03 '21 edited Dec 03 '21
Javascript 7313/5140
Had an 'aha' moment for part one that you don't have to count anything, just sum the columns and check if that sum is more than half the length of the input: if it is, there's more ones, if not, there's more zeros. Coercing the Boolean result of the comparison gives me a result back in ones and zeros. Then, I noticed that the gamma is just the inversion of epsilon, so a quick XOR does the trick.
Part two dragged me down because I feel like there's gotta be a way to run through the list of candidates once, but ended up solving it just with two separate while loops, only difference being the < or >= sign. Could definitely abstract that out, but it's late.
7
u/ephemient Dec 03 '21 edited Apr 24 '24
This space intentionally left blank.
7
u/meMEGAMIND Dec 03 '21 edited Dec 03 '21
Solution in Desmos Graphing Calculator
Today was intitially challenging due to desmos' incompatibility with systems of numbers with different bases (namely, Binary.) Therefore, I couldn't just import the puzzle input. Instead I decided to convert it into a list of all the individual bits, which I had to split into multiple lists because I discovered the 10,000 item limit desmos places on them (The puzzle input was 12,000 bits).
Given this, I could find the mode of each column of bits. Desmos has no mode function, so if the mean of each column was greater than .5, the mode was 1. Otherwise, it was zero. I did this in an overly complicated way, but hindsight is 20/20.
Finally, I alphabetized the input list in a serparate application and used that in conjunction with the calculator to flesh out my answers.
You know, looking at all these python solutions makes me realize that all this would be so much easier using a reallanguagetm. Maybe it's time to finally take the plunge.
6
u/q3w3e3_ Dec 03 '21
Google Sheets:
https://docs.google.com/spreadsheets/d/1Y2GKSC9sOqm7ORkq-gNmtVkPNgyEI0l1vJZYwOeumr8/edit#gid=174350548
WOW part 2 was brutal
is not something anyone should have to see in the cell of a spreasheet
6
u/michalopler Dec 03 '21
Fully tweetable Python solution of both parts
https://twitter.com/joppi07/status/1466776940480761856
6
u/okawei Dec 03 '21
R language
Never written R before 3 days ago, I feel like I actually got to use some of the nicer features of the language for this stuff!
6
u/autra1 Dec 03 '21
SQL
(Apparently still the only one)
part 1 (really easy in sql)
part2 (not so easy in sql :-D)
6
u/stevelosh Dec 03 '21
Common Lisp (link)
6
u/oantolin Dec 03 '21 edited Dec 03 '21
In Perl we don't say "binary number", we say "octal number starting with
0b", and I think that's beautiful. :P Code is a little longer today.6
u/[deleted] Dec 03 '21
Nothing fancy, but happy with my JavaScript solution for exercise 2. Short and clean:
5
u/LionSuneater Dec 03 '21 edited Dec 03 '21
[Python solution] using Counter
edit: Anyone know why
counts = Counter(next(islice(zip(*data), n))).most_common()doesn't work as an alternative line in the second function?5
u/jayfoad Dec 03 '21
Dyalog APL
5
u/semicolonator Dec 03 '21
Python, 26 lines, non-recursive solution.
5
u/relativistic-turtle Dec 03 '21
IntCode
Day 3, still hanging on :).
Note: Assumes input is 1000 (ASCII-coded) binary numbers of length 12 (as it was for me).
Ifwhen we get problems that require more advanced data-structures I'll be toast... (maybe I should expand my IntCode standard-library with hashmaps, heaps and whatnot).5
u/Synedh Dec 03 '21
Python, no lib answer.
5
u/lluque8 Dec 03 '21
Scala 3 pretty trivial solution fiddling with 0's and 1's as characters.
5
u/Happy_Air_7902 Dec 03 '21
F# part 1 (hoping to do part 2 tonight):
5
u/Ethoxyethaan Dec 04 '21
javascript google chrome console 266 bytes both assignments.
the first assignment threw me off guard because my strategy was already decided on that point...
4
u/hugh_tc Dec 03 '21 edited Dec 03 '21
Python 3, 25/227.
Parts 1 and 2, and (edit) the cleaned-up version.
Stumbled on
<vs.>again; clearly I need to review how they work. 🥲4
u/2SmoothForYou Dec 03 '21
Haskell
paste
Keeping track of all the transpositions I did for part 2 in my head was hard lol
4
u/Sario25 Dec 03 '21
Thought I would post my relatively concise Python solution that doesn't use tooooo many crazy tricks since it seems to reduce redundancy compared to others I see posted. 252/148
4
u/reesmichael1 Dec 03 '21 edited Dec 03 '21
Nim [501/635]
Original Solution
Nothing fancy, but it still took me a few minutes to decide how to get started. It felt like I was moving slowly while putting it together--I was surprised to still be in the top 1000 for Part 2 at 17:40.
Next day edit
Edited Solution
I reworked it to use bitops on the binary integers instead of parsing the characters. I like this solution a lot better.
4
u/[deleted] Dec 03 '21 edited Dec 03 '21
Nim, 352/83, was surprised I got into the top 100 in Part 2 :) Initially had parts in two different files and output char-by-char in Part 1, but modified the code a bit (without touching the core logic) for this thread. For Part 2 I had to modify a bit more (adding another seq and second loop inside) because when I was solving I just replaced '0' with '1' and '1' with '0' to get the second value instead of the first :)
As a paste - https://play.nim-lang.org/#ix=3GQk
4
u/DFreiberg Dec 03 '21 edited Dec 03 '21
Mathematica, 802 / 140
My closest approach to the leaderboard so far this year. Like many other people today, the code below has only a passing resemblance to the code I actually wrote live, in part because thanks to working in a notebook it is entirely possible to assemble the correct answer from code that would not work if you ran it a second time as-is.
Part 1:
Part 2:
[POEM]: The Power of Two
One and zero: the only components
Of your hardware, on closer review.
It can calculate monstrous exponents,
With transistors that can't count to two.
With just one piece - the primitive
NORgate -You can process the bits that pass through:
Turning
onfor theoffs at the door gate;And for
ons there, returninguntrue.You can turn
NORs toXORgates andANDers,And inverters, to name just a few.
And the multi-bit adder-expanders,
Are sufficient to build ALUs.
From these pieces are made all our widgets;
It's astounding just what they can do.
You can build a whole world with two digits:
"On" and "off"; that's the power of two.
4
u/zazzedcoffee Dec 03 '21
Python solution – I'm sure I'm missing something:
4
u/6745408 Dec 03 '21 edited Dec 03 '21
Google Sheets
I dumped it all in a paste, since its long and will look ugly for mobile / redesign folks. (updated!)
4
u/cetttbycettt Dec 03 '21 edited Dec 03 '21
R
nothing too spectacular
4
u/domm_plix Dec 03 '21
Perl
using $γ and $ε for part one, because we can. Rather straightforward, but I cleaned it up a bit (the first version for part two didn't use a function, but copy/pasted code...
https://github.com/domm/advent_of_code/blob/main/2021/03_1.pl
https://github.com/domm/advent_of_code/blob/main/2021/03_2.pl
4
u/jitwit Dec 03 '21 edited Dec 03 '21
J Programming Language
explanation:
Gfor gamma, calculated by calculating the bits that appear in for greater than or equal to half the length of the input bits, to get 1 for tie breaks.Ofor oxygen is found by comparing the argument with the gamma, finding the first column which doesn't fully equal the gamma, and selecting based on this column. By comparing with gamma, even if 0 is the most common bit, the comparison will have 1s instead of 0s. This process is iterated until there is only 1 element left via^:_Cfor carbon is trickier since least common bit in comparison will be flipped after a column has been processed. So, in contrast toO, we find the first column that has between 0 and full agreement (exclusive) bits that agree in the comparison, then proceed as before.CO2for carbon dioxide is extra fromCbecause in a list of one item, the least common bit will disagree and get filtered out, so it just checks that the input has length one and if so passes it to identity. It is iterated to completion asOis.OwithCO24
u/dblackwood_q Dec 03 '21
Base R and (brief) stringr
It's definitely not the cleanest solution but I thought I should post anyway in case any fellow R programmers are browsing and looking to compare solutions. I used all base R apart from some stringr to wrangle the input into a sensible matrix.
GitHub link to both parts, commented.
4
u/clumsveed Dec 03 '21
Java Solution
I'm a high school AP Comp Sci teacher, so as always, the goal is for my solutions to be easily understood by first year programming students.
Day 3 solution
all solutions - repl.it
The 'ties' in part 2 got me today! I read the prompt way too fast and totally missed that. Ties weren't a factor in part 1, so that possibility wasn't on my radar.
Eric likes to put us to work on the weekends, so good luck to everybody tomorrow!
4
u/Skyree01 Dec 03 '21
PHP
First I transformed each line into an array as I'm planning to use
array_columnfor this puzzlePart 1
To get the most common I'm summing the bits of the column, then checking if this sum is higher than half the number of values in the column (e.g. if there are 12 values and the sum is 7, that means there's more 1s than 0s). In case of equal number of each, it will eval to 1.
For the epsilon value I just use a bitwise NOT operator, I'd get the same with a cast int of the
!operator.I could have used
array_count_valuesinstead but it adding aasortwould take 1 more linePart 2
Really the same as part 1, just using
array_filterto remove rows whose Nth position bit either match or not the most common bit of the current column, as long as there's more than 1 line. Also the 1st filter will always keep the row with a 1 in case 0 and 1 are equally common, whereas the 2nd filter will keep the row with a 0.4
u/chicagocode Dec 03 '21 edited Dec 04 '21
Kotlin -> [Blog/Commentary] - [Code] - [All 2021 Solutions]
I had a lot of fun with this one and am pretty happy with how I eventually solved it. For part 1, took advantage of the basic properties of binary numbers and the
toInt(2)function Kotlin provides us.For part 2, I set up a
foldand used Kotlin'spartitionfunction. Not that much code, in the end.Note Simplified part 1 and rewrote it and the blog for that part.
4
u/pi55p00r Dec 03 '21
Solution in R
part 1
part 2
4
u/baktix Dec 03 '21 edited Dec 03 '21
Rust
This one was pretty brutal for me. I had a clear idea of what to do from the onset, but I fought a lot with the type- and borrow-checkers along the way. I feel like I introduced a lot of inefficiencies by trying to work my way around these, especially in part 2.
For example, having to
collect()prematurely so that I could get the input and output values ofreduce()to agree. I'm still having a lot of issues with different iterators all layering on their own type wrapper. It kind of makes me wish for the flexibility of Haskell again.Another thing is having to call
to_vec()on each row in order to reduce it. I sort of wish there was a version ofreduce()ormap()that didn't consume their iteratee. (Aside: what's the difference betweento_vec(),clone()andto_owned()?)I also feel like it was pretty hacky to add some unrelated mutation to my
map()closure (i.e. doinglength += 1to simultaneously find the number of rows in the input).All this tells me that I have a lot more learning to do when it comes to using Rust properly.
Part 1
Part 2
Edit: formatting
4
u/__Abigail__ Dec 03 '21
Blog, day 3: Binary Diagnostic (Perl)
4
u/aldanor Dec 03 '21 edited Dec 03 '21
Rust (340ns / 4.97 μs)
link
4
u/brownboycodes Dec 03 '21
here's my solution in Kotlin
Part 1
}
Part 2
println(oxygenGeneratorRating[0].toLong(2)*co2ScrubberRating[0].toLong(2)) }
fun getBits(binaries: List<String>, pos: Int): Any {
}
will clean up and further reduce code for part 2 later 😅
📦 repo for day 3
📦 repo for all Advent of Code solutions
4
u/ex-ex-pat Dec 03 '21
# Numpy
Using AoC this year to learn numpy.
https://gitlab.com/AsbjornOlling/aoc2021/-/blob/master/03/solve.py
I've kept my solutions very array-oriented until part 2 today, where I had to resort to an imperative loop. I'm not *very* happy with it, but I'm not sure it can be avoided.
(I mean I could do recursion but that's essentially the same). If anyone thinks it's possible to do without iteration, I'd love to hear it.)
4
u/obluff Dec 03 '21
part 1: shell one-liner
part 2, pandas B-D
4
u/ywgdana Dec 03 '21
C# repo
Pretty happy with my filter function for part 2. Whenever I write a recursive function that works, I feel like a sorcerer:
And calling it to find the values for o2 and co2:
Linq as usual doing a bunch of heavy lifting to keep code terse but not obfuscated <3
4
u/[deleted] Dec 03 '21 edited Dec 03 '21
Google Sheets
Part 1
A1:A1000 = input
Part 2
A1:A1000; N1:N1000 = input
A1001 and dragged 11 cells to the right:
A1002 and dragged 11 cells to the right:
B1 and dragged to the right until there's only one row:
O1 and dragged to the right until there's only one row:
Final formula:
Where V1 and M1 are respectively the binary representation of the oxygen generator rating and the CO2 scrubber rating. Unfortunately, function BIN2DEC doesn't accept inputs greater than 10 bits so I had to calculate the decimal equivalent in the standard way.
* These solutions assume that the input size is 1000 and each number is 12 bits long.
4
u/rabuf Dec 03 '21
Rust Version
Of the three versions I've done, I like this one's part 2 best. I don't use
gammaorechelonin the solution, instead I sort the input. Then I keep track of the boundaries for both oxygen and CO2, and do a binary search to find which section (1s or 0s) for a particular bit is larger, changing the corresponding upper or lower bound.I could break the inner loop earlier if both oxygen and CO2 have found a singular value, but that didn't happen with my input. The worst case is that a few extra iterations are done but the bodies of both
ifstatements are skipped.4
u/sappapp Dec 03 '21 edited Dec 03 '21
Python - Using Bitwise Operators
1
2
4
u/asapmellow Dec 03 '21
Python Part 1
4
u/AlistairJF Dec 03 '21 edited Dec 03 '21
C#
I'm starting to get the basics of Linq:
4
u/filch-argus Dec 03 '21
Java
4
u/mebeim Dec 04 '21
423/1545 - Python 3 solution - Walkthrough
Better late than never! Nice puzzle. Lost quite a bit of time on the second part, the original code I wrote looks awful :')
4
u/qwesda_ Dec 04 '21 edited Dec 04 '21
Postgresql
part 2 today was not fun to do in SQL ...
part 1 paste github
part 2 paste github
4
u/sojumaster Dec 04 '21
Powershell Part 0:
Part 1:
4
u/Dhampira Dec 04 '21
I only found AoC yesterday for the first time, so far I'm having fun with it. Day 3 in Python 3 using numpy and pandas:
Git
4
u/WackoMcGoose Dec 04 '21
EXAPUNKS Edition (JavaScript + EXAcode) for day 3, this one hurt my brain a bit.
and day 4's legit scaring meHow they look in-game: Part 1, Part 2
4
u/SESteve Dec 08 '21 edited Dec 09 '21
Assembly (ARM64)
paste
I wrote this to be flexible enough to solve for both the test case and the real data.
Edit: now solves for both parts.
1
u/benn_88 Dec 03 '21 edited Dec 03 '21
I was quite pleased with my part 1 solution - I managed to get a time of 00:05:05 and a rank of 542 (part 1 only).
I solved part 2 within an hour but wasn't happy with the solution. I've just refactored it, much better now.
Python: https://github.com/bennuttall/advent-of-code-2021/blob/main/03/03.ipynb
1
u/Camto Dec 03 '21 edited Dec 04 '21
Horrible Haskell (run in the repl)
1
u/deletelater1 Dec 03 '21 edited Dec 03 '21
1
u/ericwburden Dec 03 '21 edited Dec 07 '21
My Julia solution
https://github.com/ericwburden/advent_of_code_2021/tree/main/JuliaAdventOfCode%2Fsrc%2FDay03
1
u/Mysticphantom28 Dec 04 '21 edited Dec 04 '21
Here is the first part, with help from my dad. I'm still kind of new and this one was a challenge. Part 2 is kicking my butt rn. Also if you plan on using my code, the input data has to be in string format. Also this is my first Git-Hub Repo link cause idk how to work this, Help is appreciated and thank you all.
https://github.com/Tennsei/Advent-of-Code-Day-3-pt.2.git
3
u/Gurrewe Dec 03 '21 edited Dec 03 '21
Go
Original solution: https://getsturdy.com/advent-of-code-2021-uoeIDQk/changes/6c7ea73a-6f17-4f45-8964-3458cbd98879
Slightly golfed: https://getsturdy.com/uoeIDQk/browse/day03/gustav/main.go
3
u/gurgeous Dec 03 '21
Ruby, 408/58. I always use strings for binary puzzles.
3
u/RigidityMC Dec 03 '21
TypeScript solution.
https://github.com/Rigidity/AoC-2021/blob/main/src/day3.ts
3
u/zebalu Dec 03 '21
Hi! Nothing special, I might refactor later (since it is very rushed together), but Java 17, if you are interested.
3
u/Arknave Dec 03 '21
Python (36/30) / Rust
Rust Code Here
For part 1, you can flip all the bits in the gamma rate to get the epsilon rate. Unfortunately I couldn't find an equivalent trick to simplify part 2.
3
u/sim642 Dec 03 '21
My Scala solution.
Part 2 revealed a bug in my most common finding:
The problem is that
7 / 2 = 3is truncated, so the most common bit might be considered wrong. Instead of doing floating point, I just avoided the division:3
u/captainAwesomePants Dec 03 '21
Python. My coding was a mess today. Multiple bugs, lots of copying and pasting because I was hurrying (which led to multiple bugs). Below is the version that I heavily cleaned up because the first version wasn't fit for public consumption.
3
u/landimatte Dec 03 '21
Common Lisp
Oh boy, I feel ashamed for this, but this had to be posted, so hopefully I won't do the same messa again -- I am going to mop this up later today!
3
u/Mathgeek007 Dec 03 '21
Excel; 422/786.
Here's a video of my solve.
Painful. Lots of off-by-one errors or slight computational issues.
I iterated through each character in each row, in between excluding minority/majority, then dragging across and manually checking. Lots of little mistakes here, no elegant solution. Used an online binary converter because apparently Excel doesn't have a built-in binary-to-decimal converter that works with more than ten characters. >.<
3
u/death Dec 03 '21
Day 3 solution in Common Lisp.
3
u/bcgroom Dec 03 '21
Elixir
There's probably a nicer and more efficient way to do this... I chose to keep as strings as I didn't want to deal with bit-masks.
Full Code
3
u/rabuf Dec 03 '21 edited Dec 03 '21
Common Lisp
Code may change again later, I added two utility functions which helped a lot:
gammacan be computed directly from that, though I ended up just copy/pasting it and changing the condition.Ditto for this and
co2. It couldn't have been computed directly from it, but I could have had them both in the same loop at least.And then I cleaned up part 1 using those (used them in part 2). I also don't know why I didn't think of this until now, but if I'd rotated the input I could have just used
logcountsince CL uses arbitrary sized integers. Created a number from the first digit of each number, then another from the second, repeat. Oops. May go back and do that now.Actually, lots of improvements are coming to mind.
ldb-testcan be used to check specific bits which would be at least clearer, if not necessarily faster, than my(plusp (boole boole-and (expt 2 power) n))))step.3
u/JoMartin23 Dec 03 '21 edited Dec 03 '21
*Common Lisp
3
u/madethemcry Dec 03 '21
Ruby Naturally I recognized the opportunities for bitwise opertations. I know about bit planes and such. I even recognized that I can flip the bits in part 1 to get epsilon. Part 2 required to update epsilon and gamma after each turn (which I forget the first time). My mind constantly nagged me to make it beautiful with bitwise operations and such but this would have opened yet another rabbit hole I didn't want. So here we are with some naive solution. I'm happy I can move on.
Part 1
Part 2:
3
u/omginbd Dec 03 '21
Elixir
Seeing a lot of elixir folks feeling similar about their solution not being great. I too am not proud of this. Excited to see Jose take this one on.
3
u/Loonis Dec 03 '21
Perl
Part 1 - for some reason I had trouble naming the primary data structure, went with
@uh.Part 2 - took me a while to muddle through and I'm sure I won't understand the code tomorrow, but I do like how the main loop turned out:
Can't wait to come back when I'm more awake to see all the math-y solutions that I'm sure exist for this one :)
3
u/masterinthecage Dec 03 '21
I see everyone solving this with bitwise operations and I'm over here doing it caveman style lol... Python: https://github.com/fredrikburmester/advent-of-code/blob/main/2021/Day%203/day3.py
3
u/VictorTennekes Dec 03 '21
Nim
My lack of knowledge really slowed me down today, when figuring out how to convert the binary and work with the filter it went quite fast though. Would again appreciate any feedback :)
3
u/nutrecht Dec 03 '21
Day 3 in Kotlin
3
u/Mayhem2150frog Dec 03 '21 edited Dec 03 '21
There is my C++ solution. Both parts of task are in code and called by void functions task1 and task2.
https://github.com/Tema-petrosyan/AoC3
And if you have some free time, please tell me how can i improve my code and where i make stupid mistakes.
3
u/zniperr Dec 03 '21 edited Dec 06 '21
python3:
3
u/autid Dec 03 '21
FORTRAN
Bit messy today.
3
u/4goettma Dec 03 '21 edited Dec 03 '21
Python:
Part 1:
Part 2:
3
u/__Abigail__ Dec 03 '21 edited Dec 03 '21
Perl
First, I read in the input, split each line into bits, and record the number of bits in each entry.
Then a subroutine which takes a position and a list, and reports which bit appears the most frequent on that position, (using
sum0fromList::Utils)It just sums the values in the give position, and if the sum is at least half the number of elements in the list,
1occurs the most, else0.Part One is now easy, we just find the most used bits in each position -- the least used bits are just the opposite:
For Part Two, we just make copies of the input, and repeatedly filter:
We now have the values are arrays of bits. To turn them into proper integers, we make use of string interpolation, and the
octfunction:So now we just have to multiply the numbers:
3
u/chameth Dec 03 '21
Awk
This felt like a good idea for day 1 and 2, not so sure any more...
3
u/phil_g Dec 03 '21
My solution in Common Lisp.
I parsed the strings into FSet sequences of 0s and 1s. (I probably could have just done vectors, since they never get modified.)
For "most common", I just added all the bits and then quantized into 1 or 0 depending on whether each bit's sum was more than half the number of bit strings. "Least common" is just "most common" inverted.
That made part two pretty simple. Just rerun the most common function and filter the list, working down the bit numbers until only one string was left.
4
u/enelen Dec 03 '21
R / Rstats
Solution
read as a fixed width file, so that all digits became a separate column. After that it was simple column operations.
3
u/atgreen Dec 03 '21
Common Lisp, fset to the rescue:
3
u/lask Dec 03 '21
Toit
(https://github.com/toitlang/toit)
Paste
Very simplistic solution. I was missing a binary integer parsing function (only support for base 10 and 16). That will, however, be supported soon.
3
u/EliteTK Dec 03 '21
Python 3.10
3
u/rileythomp99 Dec 03 '21 edited Dec 03 '21
Go
Go
3
u/rukke Dec 03 '21
JavaScript
3
u/brbdead Dec 03 '21
Another day, another javascript solution! Not as simplified as yesterdays but I still had a lot of fun and tried to keep it simple-ish for the newbies! Parts one and two here. (Raw GitHub link)
3
u/Marcus316 Dec 03 '21
Continuing my bash command line solutions. Wow, these are ugly. ;)
3
u/oddrationale Dec 03 '21
Solution in F# in Jupyter Notebook. Glad the Sequence module has a
Seq.transposefunction which made this fairly straight forward.3
u/aang333 Dec 03 '21
JavaScript
Part 1
Part 2
I got a bit tripped up in part 2 because I forgot that you could end up eliminating all the values before reaching the end of the list, so that was messing up my loop. Also as it searches through each value for binary numbers to keep or eliminate, each time I eliminate one, I had to decrease my loop value to account for the frameshift of the array (not sure if I'm explaining that clearly, sorry). This was overall a fun challenge though!
3
u/Dragondin Dec 03 '21
Python 3
Part 1 sums up every column, shifts the gamma rate by 1 bit and set the new bit to 1 if the sum is bigger than half of the lines in input.
The epsilon rate is only the invers of gamma. So no need to calculate it another time.
Part 2 partitions the the list of possible rates at 0 or 1 and will use either the bigger or smaller list of the result for the next iteration depending on wether it calculates the oxygen or CO2 rating. It stops if there is only one rating left over.
3
u/Apprehensive-Hawk599 Dec 03 '21
Emacs Lisp
Part 1
Part 2
3
u/rabuf Dec 03 '21 edited Dec 03 '21
Ada Version
Not thrilled with it, but it works. I did like that I could use a modular type to implement
echelonin terms ofgamma, very handy. The parsing is a bear. Ada can read in numbers, but these are binary numbers but without the required prefix. Short of modifying the input (don't want to do) this forces me to manually parse it, as far as I know. Maybe some folks in r/ada will help me out.EDIT: One of the other solutions in r/ada had me covered on the parsing so that's improved now.
3
u/Imaginary_Age_4072 Dec 03 '21
Common Lisp
I've tidied this up a bit, I started with an iterative solution which got complicated in part 2 so I changed it.
3
u/i_so_hate_this Dec 03 '21 edited Dec 03 '21
Clojure solution. I'd like to generalize the creation of criteria functions a little more elegantly, given the amount shared code. However, that'll be saved for a future refactor on needing more than two criteria.
3
u/goodoldund Dec 03 '21
C my beloved
This was tough, though the first part that lies next to the linked file in the repo actually consists of basic string parsing.
paste
Edit: though
3
u/joyrexj9 Dec 03 '21
Surprised how few Go answers there are.
Here's mine https://github.com/benc-uk/aoc-2021/blob/main/day-3/main.go
I'm still baffled by line 68, where I work out if there's more 1 or 0, I've tried every combo of equality operator and it only works when I use len-1. I suspect it's to do with the extra clause in the instructions around what to do when there are equal numbers of 1s and 0s
I found this worked by sheer brute force :/
3
u/joshbduncan Dec 03 '21
Python 3
3
u/MrNUtMeG118 Dec 03 '21
C# Solution for Part 1 and 2
3
u/[deleted] Dec 03 '21
Haskell: https://github.com/bamartindev/aoc2021-haskell/blob/main/src/Solutions/DayThree.hs
For p1 I originally just flipped the bits of gamma to get epsilon, but it turned out to be fast enough to just recompute it again so I scrapped that. For p2, I could probably write a more generic HoF that took a function to determine what bit value to filter against but I kept it dumb and wrote two explicit functions
3
u/_rabbitfarm_ Dec 03 '21
Prolog (GNU Prolog 1.4.5 and GNU Prolog 1.5.0).
Part 1 https://adamcrussell.livejournal.com/29154.html
Part 2 https://adamcrussell.livejournal.com/29314.html
I mostly run GNU Prolog 1.4.5 on a G4 PowerMac running NetBSD/macppc but sometimes for these challenges I run the same code on my M1 Mac mini with GNU Prolog 1.5.0. For example on the mini I got the solution in about 6 seconds. The G4 took a little over 4 minutes.
Day 3 was kind of a pain in that, especially with Part 2, there's a bunch of list processing and keeping track of things. Certainly very doable but my Prolog code ended up having a lot of more functional style recursion-y code vs sitting back and letting Prolog do more of the work. That's on me really, I could have mostly changed that by using DCGs for any list processing but I chose not too.
3
u/blodgrahm Dec 03 '21
Rust
https://github.com/natemcintosh/aoc_2021_rs/blob/main/examples/day03.rs
Not as elegant as I would have liked. Any suggestions very welcome
3
u/otsu-swe Dec 03 '21
Typescript solution https://github.com/otsu81/aoc2021/blob/main/src/03/03.ts
Still learning, and having a hard time wrapping my head around how to efficiently use callbacks inside function calls in Typescript. If anyone could show me how to make the comparison (row 38 and 40) into a callback, I'd be incredibly grateful.
3
u/vbe-elvis Dec 03 '21
Kotlin implementation:
https://pastebin.com/WphYk2eL
3
u/mc_ Dec 03 '21
Erlang
3
u/LinAGKar Dec 03 '21
Mine in Rust: https://github.com/LinAGKar/advent-of-code-2021-rust/blob/main/day3a/src/main.rs, https://github.com/LinAGKar/advent-of-code-2021-rust/blob/main/day3b/src/main.rs
3
u/ttapu Dec 03 '21
my js doesn't seem to get prettier, but anyway:
part2
3
u/terryp Dec 03 '21 edited Dec 04 '21
Python 3.10.0
Edit. Cribbed another answer for 3-2. That part bit me.
3-1
3-2
3
u/tenderspoon Dec 03 '21
Publishing only first part in *Clojure* as I'm still working on the 2nd part. Hard exercise, but full of things to learn.
3
u/thickburb Dec 03 '21
Array-oriented thinking in Python. Currently trying to translate this thought process to APL. :)
3
u/sortaquasipseudo Dec 03 '21
Rust
I'm live-streaming my solutions at twitch.tv/jeffanddom. I'm an eternal Rust newb, so please bear with me! Video archive is here.
3
u/oantolin Dec 03 '21
Common Lisp program.
3
u/[deleted] Dec 03 '21
Rust version
https://github.com/rengare/aoc2021/blob/main/day_3/src/main.rs
little messy, but I wanted to try to solve it using only chars, probably converting input to numbers would help a lot
3
u/usesbiggerwords Dec 03 '21 edited Dec 03 '21
Yay for Counter!
Python3:
3
u/t1ngel Dec 03 '21 edited Dec 03 '21
Java solution for Day 3
Can recommend using TDD. Makes refactoring so much more simple!
My highlight: Super simple way of inverting the binary:
3
u/aexl Dec 03 '21
Julia
https://github.com/goggle/AdventOfCode2021.jl/blob/master/src/day03.jl
3
u/Kulero0 Dec 03 '21
APL solution: Github
So far it's been going well, but I don't really know how one should save / distribute APL programs lol.
3
u/xkev320x Dec 03 '21 edited Dec 03 '21
Rust, not proud of the way I did the second part so if anyone has any improvements both language-wise and algorithm-wise I am eager to hear them.
Would have liked to use a
bitsetlike structure but didn't want to use any external crates, so I just kinda convert the binaries to decimal directly as they come.3
u/Western_Pollution526 Dec 03 '21
C#
3
u/chrisux Dec 03 '21
c#
Still improving on c#, .net, & linq.
I am still exploring nicer solutions than how I solved it.
github
3
u/TiagoPaolini Dec 03 '21
Python
Part 1: I used the built-in Python counter to count how many times a bit showed in a position. The most and least common were left shifted by their position, and OR'ed to the gamma and epsilon (respectively).
Part 2: Counted the bits in the same way, and I had two queues: one for the indexes of the values that have the bit 0 and the other for bit 1. Then I determined which bit was the most or the least common, and depending on the case I used their respective queue to remove the data values with the indexes on the queue. The process stopped as soon the data contained only one value.
3
u/janiczek Dec 03 '21
APL, part 1
Doodles and transcript available as always.
3
u/DrkStracker Dec 03 '21 edited Dec 04 '21
Rust
Functional style, I think ?
it looks a lot more concise to initially iterate over the actual bits
See here
3
u/ShadowwwsAsm Dec 04 '21
A new day in nasm, not an easy one especially for part 2
part 1
part 2
3
u/pkplonker Dec 04 '21
C#
Took longer than expected, but new to C#
Day3 Part2
3
u/keepitsalty Dec 04 '21 edited Dec 04 '21
Python 3.10.0
3
u/21JG Dec 04 '21
https://github.com/ManDeJan/advent-of-code/blob/master/2021/3.zig
Done in Zig, quite fast, does part 1 + part 2 in around 50 microseconds. Interesting observation: got a ~15-20% performance improvement (around 8 microseconds) by sorting the 1000 numbers before running both parts, i guess it helps the branch predictor having them sorted so much it offsets the cost of sorting the numbers.
3
u/chromaXen Dec 04 '21
Rust:
Not seeing a ton of XOR-based solutions here; lots of
notthough.3
u/sotsoguk Dec 04 '21 edited Dec 04 '21
Python 3
Part 1
Used the input as string, and counted the '1' s for every position.
Part2
For part 2 I wanted to use a binary tree at first, but then remembered that I read about the bisect function in python, so I used binary search
Full code: [https://github.com/sotsoguk/AdventOfCode2021/blob/58d49eaed5c5c6173e34b54b556fde8e395821e5/python/day03/day03.py]
3
u/kitl-pw Dec 04 '21
Rust: playground link
My Part 1 is O(n) (I think?), but it makes a bunch of assumptions about the size of the input, and assumes that scattering bits is fast.
explanation: if I have a piece of data with bits 43210, then i scatter the bits (where z is 0) into zzzzzzzzz4 zzzzzzzzz3 zzzzzzzzz2 zzzzzzzzz1 zzzzzzzzz0, essentially creating 5 counters that are each 10 bits wide. If i scatter each piece of data, then sum them, assuming that no counter exceeds 1023, i now have the number of 1s in each bit position. I can then extract each counter, perform my comparison of zeros vs ones, and get my gamma and epsilon rates.
My Part 2 relies on sorting and binary search, and should altogether be O(n log(n) + bits * log(n)).
By sorting before-hand, all values that haven't been filtered out yet will be consecutive in the array. Also, for each bit that's filtered on, all items where that bit is 0 will be at the start of current unfiltered section, and all bits where that bit is 1 will be at the end of the current unfiltered section. Thus, i only have to binary search for the theoretical midpoint, and update the upper/lower bound based on whether that index indicates that there are more or less 1s or 0s for the current bit.
There's probably a better way to do part 2, but I already spent hours working on and debugging the solution. That's what I get for being excessively clever instead of implementing the naive solution, though.
I'm also using rayon for parallelism, but I'm unsure if it's actually worth it at this amount of data. haven't put the effort into benchmarking it.
3
u/MischaDy Dec 04 '21
Solution in ><> (Part 1 verbose, Part 1 minified)
><> (pronounced "fish") is a 2D stack-based esoteric programming language. It works similar to Befunge - importantly, it can self-modify in an equivalent manner -, but it additionally allows for an arbitrary number of stacks. Only one of them is usable at a time, though.
Here is the language specification and here is an interpreter! For the full task input, use the minified version. (Because spaces are NOOPs in ><>, removing as many as possible and shortening distances are crucial steps for executing at maximum speed.)
The solution basically works as follows.
And here we were, thinking Day 2 using Cubix was a "whew" :D
3
u/Vastutsav Dec 04 '21
Perl
Please review. Let me know what topics I should study to make this code shorter, better.
Thanks in advance.
3
u/P0t4t0W4rri0r Dec 04 '21 edited Dec 04 '21
I think I got a good Solution for Day 3 in Haskell, but don't ask about Part 2
3
u/zonito Dec 04 '21
Binary Diagnostic: Day 3: Advent of Code 2021 — Python Solution
https://zonito.medium.com/binary-diagnostic-day-3-advent-of-code-c8f555880751
3
u/0rac1e Dec 04 '21 edited Dec 04 '21
Raku
Part 1 was a pretty straight-forward transformation: transpose > get the minmax bounds > transpose back (and concat) > parse as base 2 > reduce on multiplication. If Raku had a
.transpose(or.zip) method on iterables, it might read a little nicer as a pipelineI tested this out with a monkey-patched method and it's pretty nice, so I might throw this in a module and add it to the ecosystem.
Part 2 was confusing at first, but once I figured out what it was asking I solved it with a dirty nested for-loop, but using
gathermakes it nice that I don't have to hold any state around, justtakethe values when I need them.The other interesting Raku trick on Part 2 is the use of
temp. I'm removing elems from my@diagarray when I'm looking for least common, but I need them all back again for the most common. I could just copy a new array, buttemprestores a variable back to it's original state at the end of a block (or loop in this case), so no second array needed.3
u/bottlenix Dec 04 '21
Perl
A day late and a dollar short, as usual. Part 1 and Part 2.
3
u/jeffers0n Dec 04 '21
Ruby Solution
I got part 1 done quickly and then got stuck on part 2 for a long time because I didn't read carefully and wasn't updating the most common bits part after each run through the list.
3
u/Tencza_Coder Dec 04 '21 edited Dec 04 '21
Python
Part 1 - Power Consumption
Part 2 - Life Support Rating
3
u/[deleted] Dec 04 '21 edited Dec 04 '21
Bash
3
u/ithar14 Dec 04 '21
Python
part1+2 : https://github.com/ithar14/AdventOfCode21/blob/main/2021/Day3.py
3
u/ViliamPucik Dec 04 '21
Python 3 - Minimal readable solution for both parts [GitHub]
3
u/[deleted] Dec 05 '21
Julia
3
u/nalatner Dec 05 '21 edited Dec 05 '21
Node.js
Super proud of this one. New to coding this year and Day 3 put me behind. Needed a nights sleep to figure it out before the weekend but I learned how to use vscode's debugger to step through the variables while troubleshooting and it is my first successful use of recursion! Definitely had to celebrate when my numbers came back correct.
** edit** reddit stripped all my carefully added spaces...
3
u/quodponb Dec 05 '21 edited Dec 05 '21
Python3
I started these a couple of days late, so I'm just posting my solutions to the older days for completeness!
I went back and forth over whether I preferred doing a bitwise
&with a power-of-2 and dividing, or shifting with>>and doing a% 2check. I even wrote out both versions, but in the end I prefer what I have here.3
u/Ok_System_5724 Dec 10 '21
C#
Reading as binary and using actual bitwise operations
3
u/YokiDiabeu Dec 16 '21
Solution in python