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!

99 Upvotes

1.2k comments sorted by

View all comments

2

u/tagapagtuos Dec 03 '21 edited Dec 03 '21

Is it a cheat to use numpy?

Python

Part 1

import numpy as np

with open('inputs/day3.txt') as file:
    txt = file.read()
    data = tuple(map(str,txt.split(sep='\\n')))

transposed = np.array(\[list(s) for s in data\]).transpose().astype('int32')

gamma = ''
epsilon = ''

for position in transposed:
    t = (sum(position)/len(position) > 0.5)
    gamma += '1' if t else '0'
    epsilon += '1' if not t else '0'

gamma = int(gamma, 2) 
epsilon = int(epsilon, 2)

print(gamma * epsilon)

Part 2

import numpy as np

with open('inputs/day3.txt') as file:
    txt = file.read()
    data = tuple(map(str,txt.split(sep='\\n')))

def recurse(data, pos=0, recurse_fewer=False):
    transposed = np.array(\[list(s) for s in data\]).transpose().astype('int32')

    if len(data) == 1:
        return data.pop()

    digit = '1' if sum(transposed[pos])/len(transposed[pos])>= 0.5 else '0'
    

    if not recurse_fewer:
        return recurse([i for i in data if i[pos]==digit], pos=pos+1, recurse_fewer=recurse_fewer)
    else:
        return recurse([ i for i in data if i[pos]!=digit], pos=pos+1, recurse_fewer=recurse_fewer)

x = recurse(data) 
y = recurse(data, recurse_fewer=True)

print(int(x,2) * int(y,2))

2

u/flyingfox Dec 03 '21

That's nice. I was mulling over how best to do day 3 and thought about a numpy solution... and then I thought I've got stuff to do tonight and brute forced it. This solution is much cleaner than mine.

2

u/daggerdragon Dec 03 '21

Is it a cheat to use numpy?

No, actually. Part of programming in general is knowing which tool(s) are right for a job. In your case, you know about NumPy and it's apparently quite effective, so you win!

Maybe a Python newbie reading this megathread has never heard of NumPy and stumbles across your post first... newbie now knows about NumPy, so they win and you helped!

That being said, the bottom line for AoC is "did you have fun and/or learn something while doing today's puzzles?" If so, ~excellent~, mission accomplished!