Added 2021 (python)
This commit is contained in:
1000
2021/03/input
Normal file
1000
2021/03/input
Normal file
File diff suppressed because it is too large
Load Diff
55
2021/03/prog.py
Normal file
55
2021/03/prog.py
Normal file
@ -0,0 +1,55 @@
|
||||
VERBOSE = False
|
||||
|
||||
def get_input(sample = False, part = 1):
|
||||
global n_bits
|
||||
with open(f'sample_p{part}' if sample else 'input', 'r') as f:
|
||||
tmp = f.readlines()
|
||||
n_bits = len(tmp[0]) - 1
|
||||
return [int(line.strip(), 2) for line in tmp]
|
||||
|
||||
def verbose(s):
|
||||
if VERBOSE:
|
||||
print(s)
|
||||
|
||||
|
||||
def filter_by(most, inp):
|
||||
global n_bits
|
||||
for i in range(n_bits - 1, -1, -1):
|
||||
dic = {0: [], 1: []}
|
||||
for n in inp:
|
||||
dic[(n >> i) & 1].append(n)
|
||||
|
||||
verbose(dic)
|
||||
if len(dic[1]) >= len(dic[0]):
|
||||
inp = dic[1 if most else 0][:]
|
||||
else:
|
||||
inp = dic[0 if most else 1][:]
|
||||
|
||||
if len(inp) == 1:
|
||||
return inp[0]
|
||||
|
||||
def result(inp, part = 1):
|
||||
global n_bits
|
||||
if part == 1:
|
||||
# print(n_bits)
|
||||
tot = len(inp)
|
||||
gamma = eps = 0
|
||||
for i in range(n_bits):
|
||||
ones = 0
|
||||
for n in inp:
|
||||
ones += (n >> i) & 1
|
||||
|
||||
a = 1 if ones > tot/2 else 0
|
||||
gamma |= a << i
|
||||
|
||||
eps = (2**n_bits - 1) ^ gamma
|
||||
return eps * gamma
|
||||
else:
|
||||
ox = filter_by(True, inp)
|
||||
co = filter_by(False, inp)
|
||||
verbose(f"{ox = }, {co = }")
|
||||
return ox * co
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(result(get_input(), part = 2))
|
12
2021/03/sample_p1
Normal file
12
2021/03/sample_p1
Normal file
@ -0,0 +1,12 @@
|
||||
00100
|
||||
11110
|
||||
10110
|
||||
10111
|
||||
10101
|
||||
01111
|
||||
00111
|
||||
11100
|
||||
10000
|
||||
11001
|
||||
00010
|
||||
01010
|
13
2021/03/test.py
Normal file
13
2021/03/test.py
Normal file
@ -0,0 +1,13 @@
|
||||
from prog import *
|
||||
import unittest
|
||||
|
||||
class Tests(unittest.TestCase):
|
||||
def test_input(self):
|
||||
self.assertEqual(get_input(sample = True), [4, 30, 22, 23, 21, 15, 7, 28, 16, 25, 2, 10])
|
||||
|
||||
def test_part1(self):
|
||||
self.assertEqual(result(get_input(sample = True)), 198)
|
||||
|
||||
def test_part2(self):
|
||||
self.assertEqual(result(get_input(sample = True), part = 2), 230)
|
||||
|
Reference in New Issue
Block a user