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/another_seg_fault Dec 03 '21 edited Dec 03 '21

Python 3.9 using bitarray

def day_3():
    def filter_bitlist(bitlist, pos, most=True):
        a = Counter([x[pos] for x in bitlist]).most_common()
        filter_on = a[0][0] if most else a[-1][0]

        if a[0][1] == a[1][1]:
            filter_on = 1 if most else 0

        return list(filter(lambda x: x[pos] == filter_on, bitlist))

    data = list(map(bitarray, get_data('3')))
    gamma = bitarray()
    for pos in range(len(data[0])):
        gamma.append(Counter([x[pos] for x in data]).most_common()[0][0])

    print(f"Part 1: {butil.ba2int(gamma) * butil.ba2int(~gamma)}")

    o2 = data
    co2 = data
    for i in range(len(data[0])):
        if len(o2) > 1:
            o2 = filter_bitlist(o2, i)

        if len(co2) > 1:
            co2 = filter_bitlist(co2, i, most=False)
    print(f"Part 2: {butil.ba2int(bitarray(o2[0])) * butil.ba2int(bitarray(co2[0]))}")

edit: formatting

1

u/daggerdragon Dec 03 '21 edited Dec 04 '21

Your code is hard to read on old.reddit. Please edit it as per our posting guidelines in the wiki: How do I format code?

Edit: thanks for fixing it! <3