DEV Community


Advent of Code 2020: Python Solution Day 13

qviper profile image Viper ・1 min read

This is a day 13 and again I forgot about the challenge but at last, I did it. First part was easy but for the second part I took a help from Reddit comment here.
I have uploaded all my 2020 solution on this repository.

Please share your solution too.

Part 1

with open("day13.txt", "r") as fp:
    lines = fp.readlines()
timestamp = int(lines[0][:-1])
bus_ids = [int(x) for x in lines[1].split(",") if x.isdigit()]

import numpy as np
timestamps = range(timestamp-50, timestamp+50)
valid = np.inf
diff = np.inf
bus_id = np.inf

for time in timestamps:
    for bus in bus_ids:
        if time%bus==0:
            d = abs(time-timestamp)
            if time>timestamp and d < diff:
                valid = time
                diff = d
                bus_id = bus


Enter fullscreen mode Exit fullscreen mode

Second part

start = int(LINES[0])
busses = ["x" if x == "x" else int(x) for x in LINES[1].split(",")]

def part2():
    mods = {bus: -i % bus for i, bus in enumerate(busses) if bus != "x"}
    vals = list(reversed(sorted(mods)))
    val = mods[vals[0]]
    r = vals[0]
    for b in vals[1:]:
        while val % b != mods[b]:
            val += r
        r *= b
    return val
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

Editor guide