Browse Source

Added days 4 and 5

master
Noëlle Anthony 6 years ago
parent
commit
5223acc3a9
4 changed files with 210 additions and 0 deletions
  1. 38
    0
      04a-jpaul.py
  2. 87
    0
      04a.py
  3. 35
    0
      05a.py
  4. 50
    0
      05b.py

+ 38
- 0
04a-jpaul.py View File

@@ -0,0 +1,38 @@
from collections import defaultdict
lines = open('04in.txt').read().split('\n')
lines.sort()

def parseTime(line):
words = line.split()
date, time = words[0][1:], words[1][:-1]
return int(time.split(':')[1])

C = defaultdict(int)
CM = defaultdict(int)
guard = None
asleep = None
for line in lines:
if line:
time = parseTime(line)
if 'begins shift' in line:
guard = int(line.split()[3][1:])
asleep = None
elif 'falls asleep' in line:
asleep = time
elif 'wakes up' in line:
for t in range(asleep, time):
CM[(guard, t)] += 1
C[guard] += 1

def argmax(d):
best = None
for k,v in d.items():
print("{}: {}".format(k,v))
if best is None or v > d[best]:
best = k
return best

best_guard, best_min = argmax(CM)
print (best_guard, best_min)

print (best_guard * best_min)

+ 87
- 0
04a.py View File

@@ -0,0 +1,87 @@
import re

def main(lines):
""" Sort the input by date/time, then find the best guard/minute combination

Note: the example answer is WRONG!
"""
# [1518-09-25 00:28] falls asleep
# Don't actually care about the year, since it's always the same
# grp1 grp2 grp3 grp4 grp5
pattern = re.compile("\[[0-9]+-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+)\] (.+)")
guardptn = re.compile("Guard #([0-9]+) begins shift")

entries = []
guards = {}

for line in lines:
m = pattern.match(line)
g = guardptn.match(m.group(5))
guard = -1 if g == None else int(g.group(1))
# guard # month # day # hour # minute # activity
entries.append([guard, int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4)), m.group(5)])
entries.sort(key = lambda x: (x[1], x[2], -x[3], x[4]))
for i in range(1, len(entries)):
if entries[i][0] == -1:
entries[i][0] = entries[i-1][0]
with open("04out.txt", "w") as ofile:
for entry in entries:
ofile.write("{}\n".format(entry))
# so entries is
# [0, 1, 2, 3, 4, 5]
# #guard # month #day #hour #minute #activity
stt = -1
end = -1
for i in range(1,len(entries)):
sleeping = False
cguard = entries[i][0]
#print(cguard)
if cguard == entries[i-1][0]:
if entries[i][5] == "falls asleep":
stt = entries[i][4]
#print("{} fell asleep at {}".format(cguard, stt))
sleeping = True
elif entries[i][5] == "wakes up":
end = entries[i][4]
sleeping = False
#print("{} woke up at {} (fell asleep at {})".format(cguard, end, stt))
for q in range(stt, end):
if cguard not in guards.keys():
guards[cguard] = {}
guards[cguard][q] = 1
else:
if q not in guards[cguard].keys():
guards[cguard][q] = 1
else:
guards[cguard][q] = guards[cguard][q] + 1
else:
stt = -1
end = -1

gslp = {}
for k,v in guards.items():
maxsleeps = 0
maxmin = 0
for minute, sleeps in v.items():
if sleeps > maxsleeps:
maxsleeps = sleeps
maxmin = minute
print("{} slept the most times ({}) at minute {}".format(k, maxsleeps, maxmin))
gslp[k] = [maxmin, maxsleeps]

tguard, tmin, tsleeps = 0, 0, 0
for k,v in gslp.items():
if v[1] > tsleeps:
tguard, tmin, tsleeps = k, v[0], v[1]

print("Guard {} slept the most times ({}) at minute {}. ID * minute = {}!".format(tguard, tsleeps, tmin, tguard*tmin))

def add_sleeping(dct, mins):
pass

if __name__ == "__main__":
lines = []
with open("04in.txt","r") as f:
for line in f:
lines.append(line.strip())
main(lines)

+ 35
- 0
05a.py View File

@@ -0,0 +1,35 @@
""" Advent of Code Day 5a

"""

def comp(s1,s2):
if (s1 != s2) and s1.lower() == s2.lower():
return True
return False

def main(polymer):
opoly = polymer
do_it = True
while do_it:
olen = len(polymer)
print(olen)
for i in range(len(polymer)-1):
if comp(polymer[i], polymer[i+1]):
if i == 0: # the first two are a match
polymer = polymer[2:]
elif i == (olen - 2): # the last two are a match
polymer = polymer[:-2]
else: # the match is in the middle
polymer = polymer[:i] + polymer[i+2:]
break
if olen == len(polymer): # we didn't reduce polymer's length at all
do_it = False # no more matches, stop looping

print(len(polymer))


if __name__ == "__main__":
inline = ""
with open("05in.txt","r") as ofile:
inline = ofile.read().strip()
main(inline)

+ 50
- 0
05b.py View File

@@ -0,0 +1,50 @@
""" Advent of Code Day 5b

"""

from collections import defaultdict

def comp(s1,s2):
if (s1 != s2) and s1.lower() == s2.lower():
return True
return False

def main(polymer):
opoly = polymer
lens = defaultdict(int)
alphabet = "abcdefghijklmnopqrstuvwxyz"
for char in alphabet:
polymer = "".join(opoly.split(char))
polymer = "".join(polymer.split(char.upper()))
do_it = True
while do_it:
olen = len(polymer)
# print(olen)
for acter in alphabet:
if acter != char:
polymer = "".join(polymer.split("{}{}".format(acter, acter.upper())))
polymer = "".join(polymer.split("{}{}".format(acter.upper(), acter)))
print("with {}, after {}, len(polymer) is {}".format(char, acter, len(polymer)))
# for i in range(len(polymer)-1):
# if comp(polymer[i], polymer[i+1]):
# if i == 0: # the first two are a match
# polymer = polymer[2:]
# elif i == (olen - 2): # the last two are a match
# polymer = polymer[:-2]
# else: # the match is in the middle
# polymer = polymer[:i] + polymer[i+2:]
# break
if olen == len(polymer): # we didn't reduce polymer's length at all
do_it = False # no more matches, stop looping
lens[char] = len(polymer)
with open("05out.txt","a") as ofile:
ofile.write("{}: {}\n".format(char, len(polymer)))
for k,v in lens.items():
print("{}: {}".format(k,v))


if __name__ == "__main__":
inline = ""
with open("05in.txt","r") as ofile:
inline = ofile.read().strip()
main(inline)

Loading…
Cancel
Save