DEV Community

Viper
Viper

Posted on

Advent of Code 2020: Python Solution Day 14

Today's challenge was associated with binary system and it was pretty tricky too. I had to take help from here. I also have updated my repository here.

Please share your solution too.

Part 1

with open("day14.txt", 'r') as fp:
    lines = [line.rstrip() for line in fp.readlines()]

memory = {}
masks = []
curr_mask = None
curr_value = None
curr_address = None

for line in lines:
    k, v = line.split(" = ")
    if k == "mask":
        masks.append(v)
        curr_mask = v
    else:
        # get address
        curr_address = int(k[4:-1])
        curr_value = int(v)       

        bin_value = list(bin(curr_value)[2:].zfill(36))
        new_value = [0] * 36

        for i, (mask, value) in enumerate(zip(curr_mask, bin_value)):
            # do nothing if X
            if mask == "X":
                new_value[i] = value
            else:
                # change value to mask else
                new_value[i] = mask

        memory[curr_address] = int("".join(new_value), 2)
print(f"Part one solution: {sum(memory.values())}")    
Enter fullscreen mode Exit fullscreen mode

Part 2

"""
If the bitmask bit is 0, the corresponding memory address bit is unchanged.
If the bitmask bit is 1, the corresponding memory address bit is overwritten with 1.
If the bitmask bit is X, the corresponding memory address bit is floating.
"""
with open("day14.txt", 'r') as fp:
    lines = [line.rstrip() for line in fp.readlines()]

memory = {}
for line in lines:
    k, v = line.split(" = ")
    if k == "mask":
        masks.append(v)
        curr_mask = v
    else:
        # get address
        curr_address = int(k[4:-1])
        curr_value = int(v)       

        bin_add = list(bin(curr_address)[2:].zfill(36))
        new_add = ["0"] * 36

        v = len(list(bin(curr_address)[2:]))

        for i, (mask, value) in enumerate(zip(curr_mask, bin_add)):
            # if mask bit is floating then keep it floating on new address too
            if mask == "X":
                new_add[i] = "X"
            elif mask == "0":

                # change value to mask else
                new_add[i] = value
            elif mask == "1":
                new_add[i] = "1"

        new_add = "".join(new_add)

        # count floatings
        num_poss = new_add.count("X")

        flucts = []
        for i in range(2**num_poss):
            flucts.append( list(bin(i)[2:].zfill(num_poss)))

        for fluct in flucts:
            i = 0
            nadd = ""
            for a in new_add:
                if a == "X":
                    nadd+=str(fluct[i])
                    i+=1
                else:
                    nadd+=str(a)
            memory[int(nadd, 2)]=curr_value
sum(memory.values())
Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
rozbrajaczpoziomow profile image
rozbrajaczpoziomow

So I have smaller code for part 1. (I'd like to note, that instead of changing the file on-the-fly, i just assign the variable prompt as (in this case) an array of strings of every line)

import re
prompt = (input)
bitmask = -1
memory = []

def pad36(pad):
    return ('0' * (36 - len(pad))) + pad

for command in prompt:
    if(command.startswith('mask')):
        bitmask = re.findall(r'mask = (.*)', command)[0]
    elif(command.startswith('mem')):
        index = int(re.findall(r'mem\[(.*)\]', command)[0])
        value = int(re.findall(r' = (.*)', command)[0])
        valuebin = pad36(bin(value)[2:])
        finalbin = ''
        for iMask in range(0, len(bitmask)):
            if(bitmask[iMask] == 'X'):
                finalbin += valuebin[iMask]
            else:
                finalbin += bitmask[iMask]
        final = int(finalbin, 2)
        while(len(memory) <= index + 5):
            memory.append(0)
        memory[index] = final


print('[Solv]', sum(memory))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
qviper profile image
Viper

Awesome

 
qviper profile image
Viper

I think it gets more handy as we keep doing.

Collapse
 
qviper profile image
Viper

Honestly, on average 1 hour. What about you?