Chellenge 4

Challenge 4.1


In [54]:
myinput = '/home/fmuinos/projects/adventofcode/2016/ferran/inputs/input4.txt'

In [89]:
! wc -l inputs/input4.txt


974 inputs/input4.txt

In [82]:
def name_id_check(room):
    name = '-'.join(room.split('-')[:-1])
    tail = room.split('-')[-1]
    aidee = int(tail.split('[')[0])
    check = tail.split('[')[1][:-1]
    return name, aidee, check

def checksum(name):
    char_dict = {char: 0 for char in name}
    for char in name:
        char_dict[char] += 1
    realcheck = sorted(char_dict.items(), key=lambda x: (-x[1],x[0]), reverse=False)
    realcheck = ''.join(list(zip(*realcheck))[0][:5])
    return realcheck
    
def is_real(room):
    name, aidee, check = name_id_check(room)
    name = ''.join(name.split('-'))
    if checksum(name) == check:
        return aidee
    else:
        return 0

def sum_real_ids(path):
    with open(path,'rt') as f:
        count = 0
        for line in f:
            room = line.rstrip()
            count += is_real(room)
    return count

In [83]:
sum_real_ids(myinput)


Out[83]:
361724

Challenge 4.2


In [84]:
def write_real_rooms(inpath, outpath):
    with open(inpath,'rt') as f:
        with open(outpath, 'wt') as g:
            for line in f:
                if is_real(line.rstrip()):
                    g.write(line)

In [85]:
write_real_rooms(myinput, 'inputs/input4-filt.txt')
mynewinput = '/home/fmuinos/projects/adventofcode/2016/ferran/inputs/input4-filt.txt'

In [87]:
! wc -l inputs/input4-filt.txt


666 inputs/input4-filt.txt

In [122]:
alphabet = 'abcdefghijklmnopqrstuvwxyz'
cypher = dict(enumerate(alphabet))
revcypher = dict(map(lambda i:(i[1],i[0]), list(cypher.items())))

def shift_decypher(name, aidee):
    decypher = []
    for char in name:
        if not char == '-':
            new_char = cypher[(revcypher[char] + aidee) % 26]
            decypher.append(new_char)
        else:
            decypher.append(' ')
    return ''.join(decypher)

def write_decyphered_rooms(inpath, outpath):
    with open(inpath,'rt') as f:
        with open(outpath, 'wt') as g:
            for line in f:
                room = line.rstrip()
                name, aidee, check = name_id_check(room)
                g.write(shift_decypher(name, aidee)+' {}'.format(aidee)+'\n')

In [123]:
write_decyphered_rooms(mynewinput,'inputs/input4-decyphered.txt')

In [125]:
! cat inputs/input4-decyphered.txt | grep northpole


northpole object storage 482