aoc-2018-python

Advent of Code 2018 Solutions in Python
git clone https://git.sinitax.com/sinitax/aoc-2018-python
Log | Files | Refs | README | sfeed.txt

solve.py (1263B)


      1import sys
      2sys.path.append("../common")
      3import aoc
      4
      5data = [int(l) for l in aoc.data.split("\n")]
      6
      7def solve1(args):
      8    return sum(data)
      9
     10def solve2(args):
     11    totshift = 0
     12    fvals = list()
     13    for c in data:
     14        fvals.append(totshift)
     15        totshift += c
     16    aoc.debug("total shift: " + str(totshift))
     17
     18    doubles = list()
     19
     20    if totshift == 0:
     21        doubles.append([len(data), 0])
     22
     23    i = 0
     24    while i < len(fvals):
     25        for j in range(len(fvals)):
     26            if i == j:
     27                continue
     28            dif = fvals[j] - fvals[i]
     29            if dif % totshift == 0:
     30                inds = list([i, j])
     31                if j > i:
     32                    inds = inds[::-1]
     33                if totshift > 0: #ends on c
     34                    if fvals[inds[0]] > fvals[inds[1]]:
     35                        inds = inds[::-1]
     36                else:
     37                    if fvals[inds[0]] < fvals[inds[1]]:
     38                        inds = inds[::-1]
     39
     40                pos = (abs(dif) // totshift) * len(data) + inds[0]
     41                doubles.append([pos, fvals[inds[1]]])
     42        i += 1
     43
     44    assert(len(doubles) != 0)
     45
     46    return min(doubles, key = lambda x: x[0])[1]
     47
     48aoc.run(solve1, solve2, sols=[411, 56360])