Advent of Code Day 4

Day 4

Solution to day 4 of Advent of Code

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]:
import pandas as pd 

def read_file():
    with open(r"datafiles\aoc4input.txt",'r') as f:
        file = f.readlines()
    return sorted(file)

Part 1

Using numpy to handle the sleepy.

In [2]:
import re
import numpy as np
guard = 0
asleep = 0

#max guard number
guards = []
for i in read_file():
    if 'begins shift' in i:
        match ='#\d+', i)
sleep = np.zeros((max(guards)+1, 60))

for i in read_file():
    if 'begins shift' in i:
        match ='#\d+', i)
        guard = int([1:])
    if 'asleep' in i:
        asleep = int(i[15:17])
    if 'wakes up' in i:
        sleep[guard,asleep:int(i[15:17])] +=1

sleepyguard =   np.argmax(np.sum(sleep,axis=1))      
print(np.argmax(np.sum(sleep,axis=1)) * np.argmax(sleep[sleepyguard]))

Part 2

Continuing from above we can easily output the indices of the maximal element.

In [3]:
ind = np.unravel_index(np.argmax(sleep,axis=None), sleep.shape)