Challenge 15


In [101]:
myinput = '/home/fmuinos/projects/adventofcode/2016/ferran/inputs/input15.txt'
myinput_test = '/home/fmuinos/projects/adventofcode/2016/ferran/inputs/input15-1.txt'

Solution 15.1


In [114]:
import math
import re

def setup(myinput):
    dd = {}
    p = re.compile('has \d+')
    q = re.compile('\d+\.')
    with open(myinput, 'rt') as f:
        i = 1
        for line in f:
            total = int(p.findall(line)[0].split()[1])
            t0 = int(q.findall(line)[0].rstrip('.'))
            dd[i] = (total, -(t0 + i) % total)
            i += 1
    return dd

def lcm(args):
    x = args.pop()
    if args == []:
        return x
    else:
        y = lcm(args)
        return x * y // math.gcd(x, y)

def sieve(dd):
    N, X = list(zip(*[dd[i] for i in sorted(dd)]))
    l = lcm(list(N))
    X = list(X)
    N = list(N)
    for i in range(len(dd)-1):        
        a = X[i] + N[i]
        while((a - X[i+1]) % N[i+1] != 0):
            a += N[i]
        X[i+1] = a
        N[i+1] *= N[i]
    while(a > 0):
        a -= l
    return a + l

Test


In [115]:
dd = setup(myinput_test)
print(dd)


{1: (5, 0), 2: (2, 1)}

In [116]:
sieve(dd)


Out[116]:
5

Result


In [124]:
dd = setup(myinput)
print(dd)


{1: (17, 11), 2: (19, 9), 3: (7, 3), 4: (13, 2), 5: (5, 4), 6: (3, 0)}

In [125]:
sieve(dd)


Out[125]:
16824

Solution 15.2


In [127]:
disc = 7
total = 11
t0 = 0
dd.update({disc: (total, -(t0 + disc) % total)})
print(dd)


{1: (17, 11), 2: (19, 9), 3: (7, 3), 4: (13, 2), 5: (5, 4), 6: (3, 0), 7: (11, 4)}

Result


In [128]:
sieve(dd)


Out[128]:
3543984