aoc

Advent of Code Solutions
git clone git://git.alexkarle.com.com/aoc
Log | Files | Refs | README | LICENSE

b.py (906B) [raw]


      1 #!/usr/bin/env python3
      2 import sys
      3 
      4 def search(nums, maximum):
      5     # idx to consider
      6     i = 0
      7     while len(nums) > 1:
      8         # count just that digit in the string (rest is garbage)
      9         counts = [0, 0]
     10         for n in nums:
     11             counts[int(n[i])] += 1
     12 
     13         # filter the list down to most or least common
     14         is_zero = lambda x: x[i] == "0"
     15         is_one = lambda x: x[i] == "1"
     16         if (maximum and counts[0] > counts[1]) or (not maximum and counts[0] <= counts[1]):
     17             nums = list(filter(is_zero, nums))
     18         else:
     19             nums = list(filter(is_one, nums))
     20         i+=1
     21 
     22     return nums[0]
     23 
     24 # We need multiple iterations on this one -- save to mem
     25 if __name__ == '__main__':
     26     nums = []
     27     for l in sys.stdin:
     28         nums.append(l.strip())
     29 
     30     oxygen = int(search(nums, maximum=True), 2)
     31     co2 = int(search(nums, maximum=False), 2)
     32 
     33     print(oxygen * co2)