DEV Community

Discussion on: AoC Day 4: Repose Record

Collapse
 
aspittel profile image
Ali Spittel

Python!

May refactor later, but this problem was a little less fun for me than other ones so far, to be honest.

part 1

import re
from collections import Counter

with open('input.txt', 'r') as f:
    data = []
    for line in f:
       date = line[line.find("[")+1:line.find("]")]
       action = line.split("] ")[1].strip()
       data.append((date, action,))
    data = sorted(data, key=lambda i: i[0])

guards = {}
for time, action in data:
    time = int(time[-2:])
    if "Guard" in action:
        _id = re.findall(r'\d+', action)[0]
        if not _id in guards:
            guards[_id] = {'length': 0, 'minutes': []}
    elif action == "falls asleep":
        start = time
    else:
        guards[_id]['length'] += time - start
        guards[_id]['minutes'] += list(range(start, time))

sleep_longest = max(guards.items(),key=lambda guard: guard[1]['length'])
minutes = sleep_longest[1]['minutes']
print(Counter(minutes).most_common(1)[0][0] * int(sleep_longest[0]))

part 2

import re
from collections import Counter

with open('input.txt', 'r') as f:
    data = []
    for line in f:
       date = line[line.find("[")+1:line.find("]")]
       action = line.split("] ")[1].strip()
       data.append((date, action,))
    data = sorted(data, key=lambda i: i[0])

guards = {}
for time, action in data:
    time = int(time[-2:])
    if "Guard" in action:
        _id = re.findall(r'\d+', action)[0]
        if not _id in guards:
            guards[_id] = []
    elif action == "falls asleep":
        start = time
    else:
        guards[_id] += list(range(start, time))

max_count = 0
solution = 0
for guard, minutes in guards.items():
    if minutes:
        most_frequent = Counter(minutes).most_common(1)[0]
        if most_frequent[1] > max_count:
            max_count = most_frequent[1]
            solution = int(guard) * most_frequent[0]
print(solution)
Collapse
 
thejessleigh profile image
jess unrein

Agree that this one was less fun, and I kind of hate my Python solution, which is much muddier than yours. I don't know that I have the energy to try to do this in Go.

Collapse
 
aspittel profile image
Ali Spittel

Yeah, I like the algorithm-y ones, this one was more string parsing I think!

Thread Thread
 
jbristow profile image
Jon Bristow

It was a complicated description though, I had a lot of problems parsing what I was supposed to be finding.

Thread Thread
 
aspittel profile image
Ali Spittel

TOTALLY -- I only figured it out once I looked at the input. The graph actually totally threw me off.