Advent of Code Day 3

Day3

Solution to day 3 of Advent of Code https://adventofcode.com/2018/day/3

Data preparation

Since both part 1 and two use the same data, we create a function to read and prepare the data in the file:

In [1]:
def read_file():
    with open('datafiles/aoc3input.txt','r') as f:
        for line in f.readlines():
            id, cut =  line.split('@')
            id = ast.literal_eval(id[1:])
            start, size = cut.split(':')
            start_x,start_y = ast.literal_eval(start.strip())
            cut_x,cut_y = ast.literal_eval(size.replace('x',',').strip())
            yield id, start_x,start_y, cut_x,cut_y

Part 1

Using numpy to handle the fabric.

In [2]:
import numpy as np
import ast

fabric = np.zeros((1000,1000))

for id, start_x,start_y, cut_x,cut_y in read_file():
        fabric[start_y:start_y+cut_y,start_x:start_x+cut_x] +=1

print(len(np.where(fabric > 1)[0]))
        
118539

Part 2

Using numpy again and keeping a set of cuts that havent collided with any yet.

In [3]:
fabric = np.zeros((1000,1000))
d = set()
for id, start_x,start_y, cut_x,cut_y in read_file():
    if not np.any(fabric[start_y:start_y+cut_y,start_x:start_x+cut_x]):
        d.add(id)
    else:
        for a in np.unique(fabric[start_y:start_y+cut_y,start_x:start_x+cut_x]):
            d.discard(a)    
    fabric[start_y:start_y+cut_y,start_x:start_x+cut_x] = id
print(d)
{1270}

links

social