My solutions for Advent of Code.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
adventofcode/2020/14.py

99 lines
2.1 KiB

4 years ago
#!/usr/bin/env python
from aoc import get_input # AoC
import re # regex
4 years ago
import itertools as it
4 years ago
data = get_input(14).splitlines()
def listToString(s):
str1 = ""
for ele in s:
str1 += ele
return str1
def dectobin(num):
return format(num, "036b")
def bintodec(_bin):
return int(_bin, 2)
def parseLine(line):
if( line[0:3] == "mem" ):
address, val = re.match( r"^mem\[([0-9]+)\] = ([0-9]+)$", line ).groups()
_bin = dectobin(int(val))
return address, _bin
else:
op, mask = line.split(" = ")
return op, mask
4 years ago
def applyMask( _bin, mask, includeX=False ):
4 years ago
newbin = []
newbin[:0] = _bin
for i in range(len(mask)):
4 years ago
if( mask[i] != "X" or includeX ):
4 years ago
newbin[i] = mask[i]
4 years ago
return listToString(newbin)
4 years ago
def getallcombs(xlen):
return [list(i) for i in it.product(["0", "1"], repeat=xlen)]
def getAddressCombos(mask, addr):
addrlist = []
addrlist[:0] = addr
4 years ago
combs = getallcombs( mask.count("X") )
4 years ago
addrcombos = []
for comb in combs:
xcount = 0
4 years ago
newaddrlist = [addr for addr in addrlist]
4 years ago
for i in range( len(newaddrlist) ):
char = newaddrlist[i]
maskchar = mask[i]
if(maskchar == "X"):
newaddrlist[i] = comb[xcount]
xcount += 1
elif(maskchar == "1"):
newaddrlist[i] = maskchar
addrcombos.append( listToString(newaddrlist) )
return addrcombos
4 years ago
# Part 1 & 2
4 years ago
mem, mem2, curMask = dict(), dict(), None
4 years ago
4 years ago
for line in data:
4 years ago
address, val = parseLine(line)
4 years ago
if( address != "mask" ):
4 years ago
val = applyMask(val, curMask)
dec_val = bintodec(val)
4 years ago
mem[address] = dec_val
4 years ago
# apply mask to address
address = dectobin(int(address))
addrlist = getAddressCombos(curMask, address)
for addr in addrlist:
decaddr = bintodec(addr)
4 years ago
mem2[decaddr] = bintodec(val)
4 years ago
else:
curMask = val
4 years ago
continue
4 years ago
4 years ago
memsum, memsum2 = sum(mem.values()), sum(mem2.values())
4 years ago
4 years ago
print("Part1:", memsum)
print("Part2:", memsum2)