Last active
December 22, 2017 06:12
-
-
Save Sparrow1029/509daaf21d57be4550dfcac1507ac432 to your computer and use it in GitHub Desktop.
Advent of Code 2017 - Day 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
*.pyc | |
__pycache__/ | |
.DS_Store | |
__MACOSX__ | |
*.pyo | |
*.swp | |
adventbase.py | |
*input.txt |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
#-*- coding: utf-8 -*- | |
with open('Day1input.txt', 'r') as f: | |
puzzle = list(map(int, (list(f.read().strip())))) | |
total = 0 # Part 1 | |
if puzzle[0] == puzzle[-1]: | |
total += puzzle[0] | |
for i in range(len(puzzle)-1): | |
a, b = puzzle[i], puzzle[i+1] | |
if a == b: | |
total += a | |
print('Part 1: %r' % total) | |
# Part 2 | |
total = 0 | |
halfway = len(puzzle) // 2 | |
for i in range(len(puzzle)): | |
j = puzzle[(i+halfway) % len(puzzle)] | |
if puzzle[i] == j: | |
total += j | |
print('Part 2: %r' % total) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
with open('day2input.txt', 'r') as f: | |
# Read spreadsheet as list of rows. | |
sheet = [row.strip().split() for row in f.read().splitlines()] | |
checksum1 = 0 | |
checksum2 = 0 | |
for row in sheet: | |
ints = list(map(int, row)) | |
checksum1 += abs(min(ints) - max(ints)) # Part 1 | |
for i in range(len(ints)): # Part 2 | |
for j in range(i+1, len(ints)): | |
if ints[i] % ints[j] == 0: checksum2 += (ints[i] // ints[j]) | |
elif ints[j] % ints[i] == 0: checksum2 += (ints[j] // ints[i]) | |
print(checksum1) | |
print(checksum2) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
"""Day 3 - 2017: | |
-- Part 1 -- | |
Find the manhattan distance between given number on a grid (created by | |
spiraling values from `1` at the center) and the center point. | |
ex: | |
17 16 15 14 13 | |
18 5 4 3 2 | |
19 6 1 2 11 | |
20 7 8 9 10 | |
21 22 23->... | |
""" | |
from math import sqrt, ceil | |
# This happens to be on the bottom edge of our grid... so I hacked it | |
our_num = 325489 | |
# find the nearest whole square root (greater than the sqrt of our_num) | |
grid_side = ceil(sqrt(our_num)) | |
# Find the bottom right corner value | |
last_number = grid_side**2 | |
# Set the coordinate of our_num | |
endx, endy = last_number-(our_num + 1), grid_side | |
# Set the middle coordinate of our grid (starting value of 1) | |
startx, starty = grid_side//2, grid_side//2 | |
manhattan_distance = abs(endx - startx) + abs(endy - starty) | |
print(manhattan_distance) | |
"""-- Part 2 -- | |
I may actually have to make a node creation system: now the grid is | |
procedurally generated based on its neighbors. | |
ex: | |
147 142 133 122 59 | |
304 5 4 2 57 | |
330 10 1 1 54 | |
351 11 23 25 26 | |
362 747 806---> ... | |
""" | |
class Grid(): | |
neighbors = [(x+1, y), (x+1, y+1), (x, y+1), (x-1, y+1), | |
(x-1, y), (x-1, y-1), (x, y-1), (x+1, y-1)] | |
def __init__(self): | |
class Node(): | |
def __init__(self, val, coord): | |
self.val = 0 | |
self.coord = coord # Tuple value | |
self.direction = 0 # -1 left, 1 right, 2 up, -2 down | |
def turn(self): | |
cur_dir = self.direction | |
if cur_dir == 1 and (grid.neighbors |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
#-*- coding: utf-8 -*- | |
import itertools as itt | |
import operator | |
def spiral_pos_oneline(): | |
return itt.chain( | |
[(0,0)], | |
itt.accumulate(( | |
d for m, d in | |
enumerate(itt.cycle([(1,0),(0,1),(-1,0),(0,-1)])) | |
for _ in range(1+m//2)), lambda a,b: | |
tuple(map(operator.add, a, b)))) | |
s = spiral_pos_oneline() | |
x = 0 | |
while x < 100: | |
print(next(s)) | |
x += 1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
#-*- coding: utf-8 -*- | |
from adventbase import * | |
spiral = [[0] * 41 for x in range(41)] | |
spiral[20][20] = 1 | |
point = (20,20) | |
num = 1 | |
def drul(point, x): | |
"""Down, right, up, left""" | |
if x == 0: | |
return (point[0] + 1, point[1]) | |
if x == 1: | |
return (point[0], point[1] + 1) | |
if x == 2: | |
return (point[0] - 1, point[1]) | |
if x == 3: | |
return (point[0], point[1] - 1) | |
x = 0 | |
while num < 325489: | |
v = drul(point, (x+1) % 4) | |
if spiral[v[0]][v[1]] == 0: | |
x = (x+1) % 4 | |
point = drul(point,x) | |
else: | |
point = drul(point,x) | |
num = sum([spiral[x][y] for x,y in neighbors8(point)]) | |
spiral[point[0]][point[1]] = num | |
print(num) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
"""Day 4: check for valid passwords: no duplicate words """ | |
from collections import Counter | |
# Input file | |
with open('Day4input.txt', 'r') as f: | |
# Parse lines into lists of separate strings | |
passphrases = [s.strip().split() for s in f.read().splitlines()] | |
def valid(counter): | |
"""Test if passphrase has repeated words.""" | |
if any(x > 1 for x in counter.values()): | |
return 0 | |
return 1 | |
# Part 1 | |
total = 0 | |
for p in passphrases: | |
total += valid(Counter(p)) | |
print(total) | |
# Part 2 | |
total2 = 0 | |
for p in passphrases: | |
# sort the words in the passphrase alphabetically to make Counting possible | |
sorted_list = list(map(lambda x: ''.join(sorted(x)), p)) | |
c = Counter(sorted_list) | |
total2 += valid(c) | |
print(total2) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
"""Day 5 -- Advent of Code 2017""" | |
from sys import exit | |
# Open and parse input to form our list of jump instructions. | |
with open('Day5input.txt', 'r') as f: | |
instructions = list(map(int, [s.strip() for s in f.readlines()])) | |
# test = [0, 3, 0, 1, -3] | |
# instructions = test | |
cnt = 0 | |
cur_index = 0 | |
while True: | |
# print(test) | |
try: | |
jump_val = instructions[cur_index] | |
#print("cur_index, value: %d %d" % (cur_index, jump_val)) | |
next_index = cur_index + jump_val | |
# print("next index, value: %d %d" % (next_index, instructions[next_index])) | |
# instructions[cur_index] += 1 # PART ONE | |
instructions[cur_index] += (-1 if jump_val >= 3 else 1) # PART TWO | |
# print(instructions[cur_index]) | |
cur_index = next_index | |
# print(cur_index) | |
except IndexError: | |
break | |
cnt += 1 | |
print(cnt) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
mem_banks = [14, 0, 15, 12, 11, 11, 3, 5, 1, 6, 8, 4, 9, 1, 8, 4] | |
def increaseblk(idx): | |
global mem_banks | |
mem_banks[idx] += 1 | |
def join_ints(a_list): | |
return int(''.join(map(str, a_list))) | |
previous_states = [join_ints(mem_banks)] | |
cycles = 0 | |
while True: | |
max_block = max(mem_banks) | |
tgt = mem_banks.index(max_block) | |
iter_ = list(range(tgt+1, 16)) + list(range(0, tgt)) | |
while mem_banks[tgt] > 0: | |
idx = iter_.pop(0) | |
increaseblk(idx) | |
mem_banks[tgt] -= 1 | |
cycles += 1 | |
if join_ints(mem_banks) in previous_states: | |
break | |
else: | |
previous_states.append(join_ints(mem_banks)) | |
# PART ONE | |
print(cycles) | |
# PART TWO | |
print(cycles - previous_states.index(join_ints(mem_banks))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
#-*- coding: utf-8 -*- | |
import re | |
from itertools import combinations | |
class Node(): | |
"""Base class for our 'tower' tree nodes.""" | |
def __init__(self, name, weight): | |
self.name = name | |
self.weight = weight | |
self.weight_plus_children = weight | |
self.parent = None | |
self.children = [] | |
def set_parent(self, node): | |
if self.parent == None: | |
self.parent = node | |
else: | |
return "Already has a family." | |
def adopt(self, node): | |
index = self.children.index(node.name) | |
self.children[index] = node | |
# def __repr__(self): | |
# return "%r (weight) %r -> %r parent: %r\n"\ | |
# % (self.name, self.weight, self.children, self.parent) | |
def sum_weights(self): | |
"""Recurse through children and sum the weight of the branch""" | |
if self.children is None: | |
return self.weight_plus_children | |
else: | |
for child in self.children: | |
print("child.sum_weights()", child.get_total_weight()) | |
self.weight_plus_children += child.get_total_weight() | |
def get_total_weight(self): | |
return self.weight_plus_children | |
# test = "tzdmi (891) -> mhzwwo, mgybhs, pptdd" | |
# test2 = open('Day7TEST.txt', 'r').read().splitlines() | |
def parse_input(line): | |
weight = int(re.findall(r'\((\d*)\)', line)[0]) | |
nodes = re.findall(r'([a-z]+)+', line) | |
name = nodes[0] | |
children = nodes[1:] | |
return (name, weight, children) | |
with open('Day7input.txt', 'r') as f: | |
data = f.read().splitlines() | |
orphans = [] | |
parents = [] | |
for line in [l.strip() for l in data]: # test | |
x, y, z = parse_input(line) | |
node = Node(x, y) | |
if len(z) == 0: | |
orphans.append(node) | |
else: | |
node.children = z | |
parents.append(node) | |
for _ in range(len(orphans)): | |
kid = orphans.pop() | |
# print(kid) | |
for p in parents: | |
if kid.name in p.children: | |
p.adopt(kid) | |
kid.set_parent(p) | |
for x, y in combinations(parents, 2): | |
# print(x.name, y.name) | |
if y.name in x.children: | |
x.adopt(y) | |
y.set_parent(x) | |
parents.remove(y) | |
elif x.name in y.children: | |
y.adopt(x) | |
x.set_parent(y) | |
parents.remove(x) | |
root = parents[0] | |
print(root.name) # PART 1 | |
for kid in root.children: | |
for c in kid.children: | |
print(kid.name) | |
kid.sum_weights() | |
print(kid.get_total_weight()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pbga (66) | |
xhth (57) | |
ebii (61) | |
havc (66) | |
ktlj (57) | |
fwft (72) -> ktlj, cntj, xhth | |
qoyq (66) | |
padx (45) -> pbga, havc, qoyq | |
tknk (41) -> ugml, padx, fwft | |
jptl (61) | |
ugml (68) -> gyxo, ebii, jptl | |
gyxo (61) | |
cntj (57) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
import re | |
with open('Day8input.txt', 'r') as f: | |
data = [s.strip() for s in f.read().splitlines()] | |
register_regex = re.compile(r"([a-z]+) (dec|inc) (-?\d+) if ([a-z]+) ([><!=]+) ([-]?\d+)") | |
registers = {} # Create dict of registers and values | |
# First pass to find register names and set val to 0 | |
for line in data: | |
mo = re.search(register_regex, line) | |
rg_id = mo.groups() | |
for x in (rg_id[0], rg_id[3]): | |
if x not in registers: | |
registers[x] = 0 | |
max_held = 0 # PART TWO | |
# Second pass perform operations on registers according to puzzle instructions | |
for line in data: | |
mo = re.search(register_regex, line) | |
# print(mo.groups()) | |
r = mo.groups() | |
# print(r[3], registers[r[3]]) | |
# print(r[3:]) | |
if eval(' '.join([str(registers[r[3]]), r[4], r[5]])): | |
if r[1] == 'inc': | |
registers[r[0]] += int(r[2]) | |
elif r[1] == 'dec': | |
registers[r[0]] -= int(r[2]) | |
# print(r[0], registers[r[0]], "\n") | |
if max_held < max(registers.values()): | |
max_held = max(registers.values()) | |
print(max(registers.values())) # PART ONE | |
print(max_held) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
test_1 = "{{{},{},{{}}}}" # 1 + 2 + 3 + 3 + 4 = 16 | |
test_2 = "{<a>,<a>,<a>,<a>}" # score of 1 -- garbage | |
test_3 = "{{<a!>},{<a!>},{<a!>},{<ab>}}" # 1 + 2 = 3 | |
test_4 = "{{<!!>},{<!!>},{<!!>},{<!!>}}" # 1 + 2 + 2 + 2 + 2 = 9 | |
tests = [test_1, test_2, test_3, test_4] | |
def recording(stream): | |
global total_score | |
global group_depth | |
global collecting_garbage | |
print("Recording...") | |
while True: | |
current = stream.pop(0) | |
print(current) | |
if current == "!": | |
x = stream.pop(0) | |
print("cancelled: %s" % x) | |
# stream.pop(0) | |
continue | |
elif current == "<": | |
collecting_garbage = True | |
return | |
elif current == "{": | |
group_depth += 1 | |
continue | |
elif current == "}": | |
total_score += group_depth | |
group_depth -= 1 | |
continue | |
else: | |
pass | |
def trashing(stream): | |
global collecting_garbage | |
global piecesOfTrash | |
print("Collecting garbage...") | |
while True: | |
char = stream.pop(0) | |
print(char) | |
if char == "!": | |
x = stream.pop(0) | |
print("cancelled: %s" % x) | |
# stream.pop(0) | |
continue | |
elif char == ">": | |
collecting_garbage = False | |
return | |
else: | |
piecesOfTrash += 1 # <--- PART TWO | |
total_score = 0 | |
group_depth = 0 | |
collecting_garbage = False | |
piecesOfTrash = 0 | |
def parsing(string): | |
while string: | |
while not collecting_garbage: | |
recording(string) | |
trashing(string) | |
with open('day9input.txt', 'r') as f: | |
string = list(f.read()) | |
try: | |
parsing(string) | |
except IndexError: | |
print("Reached end of input.") | |
print("Total score: %r" % total_score) | |
print("Trash collected: %r " % piecesOfTrash) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment