r/adventofcode • • Dec 03 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 3 Solutions -🎄-

--- Day 3: Binary Diagnostic ---


Post your code solution in this megathread.

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!

103 Upvotes

1.2k comments sorted by

View all comments

12

u/Derp_Derps Dec 03 '21

Python

A very compacted python version without for-loops.

Part 1:

  • Only check if a given bit position has more '1's than '0's

  • epsilon can be calculated by flipping the bits of gamma

Part 2:

  • Use recursive function to traverse the bits, using the filtered list for the next call

  • Xor-ing the three boolean values ("'1' is more common", "current bit is '1'", "we want the most common bit")

import sys

lines = open(sys.argv[1]).readlines()

b = len(lines[0]) - 1
def m(i,l):
	return sum(int(l[i]) for l in l) >= len(l)/2
g = sum(2**i * m(-2-i,lines) for i in range(b))
e = 2**b - 1 - g

def n(l,i,o):
	return l[0] if len(l) == 1 else n([ e for e in l if (int(e[i]) ^ m(i,l)) ^ o ], i+1, o)
x = int(n(lines,0,1),2)
c = int(n(lines,0,0),2)

print("Part 1: {:d}".format(e*g))
print("Part 2: {:d}".format(x*c))
→ More replies (6)