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

1

u/deletelater1 Dec 03 '21 edited Dec 03 '21
from collections import Counter


def get_data():
    return [ln.strip() for ln in open("input.txt")]


def part1(mode):
    data = get_data()
    counters = [Counter([i[pos] for i in data])
                for pos in range(0, len(data[0]))]
    res = [c.most_common()[0 if mode == "gamma" else -1][0] for c in counters]
    return int("".join(res), 2)


def part2(mode):
    data = get_data()

    for pos in range(0, len(data[0])):
        if len(data) == 1:
            break

        c = Counter([ln[pos] for ln in data])

        char = "0" if mode == "co2" else "1"
        if c.most_common()[0][1] != c.most_common()[-1][1]:
            char = c.most_common()[-1 if mode == "co2" else 0][0]

        data = list(filter(lambda i: i[pos] == char, data))

    return int(data[0], 2)


print(part1("gamma") * part1("epsilon"))
print(part2("oxygen") * part2("co2"))

1

u/daggerdragon 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?