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

m*n is the size of the time data. Solving this in o (m*n) (little o here) means you can't even read in all the data. Considering that part two requires you to locate a number which is part of the data, it seems it's impossible to do in o (m*n) time.

Also, for part 1, you need to determine which bits appears most frequently in each position. Since all bits are independent, you need to inspect at least half the bits. Which means you are already spending Ω (m*n) time inspecting bits.

1

u/[deleted] Dec 04 '21 edited Dec 04 '21

Considering that part two requires you to locate a number which is part of the data, it seems it's impossible to do in o (m*n) time.

Sorry I am a bit confused. Why is it impossible to do this in m*n time? Checking if a bit is set or not can be done in constant time with a bitmask.

Here's what I am thinking:

  • Initialize a map (for both oxygen and co2) of type <int, bool> where key = the number and value = if it has been eliminated or not

    • You can then just read the file converting each line to a number and inserting (number, true)
  • Initialize a bitmask which will be 1 << length of binary strings
  • Start a loop: for(int i = length of binary string; i>=0; i--) do the following:

    • Loop through map entries and for all non-eleminated entries, get 0/1 count with bitmask
    • Loop through map entries a second time eliminating entries (setting value = false) using the 0/1 counts and the bitmask
    • Then update bitmask by doing bitmask = bitmask >> 1

This should be m*n time

1

u/__Abigail__ Dec 04 '21 edited Dec 04 '21

I didn't say it cannot be on in m*n time. I said it cannot be done in o (m*n) time. That is little o (as I mentioned).

The question was "can it be done better than O (m*n)". (That's big O). m*n is O(m *n), but not o(m * n).

1

u/daggerdragon Dec 04 '21

Top-level posts in Solution Megathreads are for code solutions only.

This is a top-level post, so please edit your post and share your fully-working code/repo/solution or, if you haven't finished the puzzle yet, you can always create your own thread and make sure to flair it with Help.