1
0
Fork 0

Compare commits

...

5 Commits

Author SHA1 Message Date
Lucidiot 6dd88bf923
2020 day 7 2020-12-07 09:17:15 +01:00
Lucidiot 96178dfda0
2017 day 18 2020-12-07 02:42:52 +01:00
Lucidiot b8ffad6c79
2017 day 19, WIP 2020-12-07 02:42:38 +01:00
Lucidiot 5cd65e1125
2017 day 20 part 2 2020-12-07 02:41:08 +01:00
Lucidiot 336341abce
2017 day 22 part 1 2020-12-07 02:40:23 +01:00
7 changed files with 245 additions and 15 deletions

52
2017/18/duet.py Executable file
View File

@ -0,0 +1,52 @@
#!/usr/bin/env python3
import sys
from multiprocessing import Queue
from multiprocessing.pool import ThreadPool
from collections import defaultdict
data = [l.strip().split(" ") for l in sys.stdin.readlines()]
def run(ident, rcvqueue, sndqueue):
reg = defaultdict(int)
reg['p'] = ident
pos, times_sent, played = 0, 0, None
def parse(word):
try:
return int(word)
except ValueError:
return reg[word]
while 0 <= pos < len(data) - 1:
ins = data[pos]
if ins[0] == 'snd':
played = parse(ins[1])
if sndqueue:
sndqueue.put(parse(ins[1]))
times_sent += 1
print(times_sent)
elif ins[0] == 'set':
reg[ins[1]] = parse(ins[2])
elif ins[0] == 'add':
reg[ins[1]] += parse(ins[2])
elif ins[0] == 'mul':
reg[ins[1]] *= parse(ins[2])
elif ins[0] == 'mod':
reg[ins[1]] %= parse(ins[2])
elif ins[0] == 'rcv':
if rcvqueue:
reg[ins[1]] = rcvqueue.get()
elif parse(ins[1]) > 0:
return played
elif ins[0] == 'jgz':
pos += parse(ins[2])
continue
pos += 1
return times_sent
print('Part 1:', run(0, None, None))
pool = ThreadPool(processes=2)
q1, q2 = Queue(), Queue()
p1, p2 = pool.apply_async(run, (0, q1, q2)), pool.apply_async(run, (0, q2, q1))
p1.get()
print('Part 2:', p2.get())

70
2017/19/packet.py Executable file
View File

@ -0,0 +1,70 @@
#!/usr/bin/env python3
from enum import Enum, IntEnum
import numpy as np
class Direction(Enum):
Up = (-1, 0)
Down = (1, 0)
Left = (0, -1)
Right = (0, 1)
class Character(Enum):
Void = ord(' ')
Vertical = ord('|')
Horizontal = ord('-')
Corner = ord('+')
Letter = -1
def parse_char(char):
try:
Character(char)
except:
assert chr(char).isalpha(), 'Unknown character {}'.format(chr(char))
return Character.Letter
class Packet(object):
def __init__(self, schema):
self.schema = np.array(map(lambda x: map(ord, x), schema))
self.x = 0
self.y = np.where(self.schema[0] == Character.Vertical.value)[0,0]
self.direction = Direction.Down
def __iter__(self):
return self
def __next__(self):
self.forward()
while self.current_char != Character.Letter:
self.forward()
return self.current_char
@property
def position(self):
return (self.x, self.y)
@position.setter
def set_position(self, value):
self.x, self.y = value
@property
def current_char(self):
return parse_char(self.schema[self.position])
def peek(self):
return parse_char(self.schema[self.position + self.direction.value])
def forward(self):
pass
def main():
import fileinput
p = Packet(fileinput.input())
print(''.join(p))
if __name__ == '__main__':
main()

1
2017/19/requirements.txt Normal file
View File

@ -0,0 +1 @@
numpy>=1.15

View File

@ -3,11 +3,6 @@
def man_dist(tup):
return sum(map(abs, tup))
import sys
import re
pattern = re.compile(r"<([0-9-]*),([0-9-]*),([0-9-]*)>")
data = [[(int(c[0]), int(c[1]), int(c[2])) for c in p] for p in [pattern.findall(l.strip()) for l in sys.stdin.readlines()]]
def update_particle(p):
return (
tuple(map(sum, zip(p[0], p[1]))),
@ -15,12 +10,36 @@ def update_particle(p):
p[2],
)
while True:
data = list(map(update_particle, data))
min_dist, min_p = None, None
for i, particle in enumerate(data):
md = man_dist(particle[0])
if min_p is None or md < min_dist:
min_p, min_dist = i, md
def part1(particles):
stability = 0
previous, min_p = None, None
while stability < 300:
previous = min_p
stability += 1
min_dist = None
particles = list(map(update_particle, particles))
for i, particle in enumerate(particles):
md = man_dist(particle[0])
if min_p is None or min_dist is None or md < min_dist:
min_p, min_dist = i, md
if previous != min_p:
stability = 0
print(min_p)
def part2(particles):
number = len(particles)
while True:
particles = list(map(update_particle, particles))
positions = next(zip(*particles))
if len(positions) != len(set(positions)):
particles = list(filter(lambda p: positions.count(p[0]) == 1, particles))
number = len(particles)
print(number)
if __name__ == '__main__':
import sys
import re
pattern = re.compile(r"<([0-9-]*),([0-9-]*),([0-9-]*)>")
data = [[(int(c[0]), int(c[1]), int(c[2])) for c in p] for p in [pattern.findall(l.strip()) for l in sys.stdin.readlines()]]
run = part2 if any(arg in map(str.strip, map(str.lower, sys.argv)) for arg in ('-c', '--collisions')) else part1
run(data)

19
2017/22/virus.py Executable file
View File

@ -0,0 +1,19 @@
#!/usr/bin/env python3
import sys
from collections import defaultdict
data = [l.strip() for l in sys.stdin.readlines()]
grid = defaultdict(bool)
for i, row in enumerate(data):
for j, col in enumerate(row):
grid[complex(j, i)] = (col == "#")
pos, d = complex(len(data) // 2, len(data[0]) // 2), 1j
becomeinfected = 0
for _ in range(10000):
if grid[pos]:
d *= 1j
else:
d *= -1j
becomeinfected += 1
grid[pos] = not grid[pos]
pos += d
print(becomeinfected)

69
2020/7/day7.lua Normal file
View File

@ -0,0 +1,69 @@
#!/usr/bin/env lua
--[[
Representation in both ways:
The input mentions what bags a bag can contain,
we store both what bags a bag can contain and
what bags can contain a bag and in which amount.
Part 2 requires the former and part 1 requires the latter.
--]]
local containers = {}
local contains = {}
for line in io.lines() do
local bag_end, contain_start = line:find(" bags contain ")
local bag_color = line:sub(1, bag_end - 1)
contains[bag_color] = {}
for count, color in line:sub(contain_start + 1):gmatch("(%d+) (%w+ %w+) bag") do
if not containers[color] then
containers[color] = {}
end
containers[color][bag_color] = count
contains[bag_color][color] = count
end
end
--[[
For part 1, we build a set of bags that can contain the shiny gold bag.
We will iterate over and over on this set until we no longer find any new
bag colors that can contain others bags that can contain the shiny gold bag.
--]]
local part1set, found = {}, 0
for color, _ in pairs(containers["shiny gold"] or {}) do
part1set[color] = true
found = found + 1
end
local found_in_iteration = 0
repeat
found_in_iteration = 0
for known_color, _ in pairs(part1set) do
for color, _ in pairs(containers[known_color] or {}) do
if not part1set[color] then
found_in_iteration = found_in_iteration + 1
found = found + 1
part1set[color] = true
end
end
end
until found_in_iteration < 1
print(found)
--[[
For part 2, we use a recursive function to find how many bags a single bag can hold.
We use a table to provide memoization, gotta go fast.
--]]
local part2memo = {}
local function count_bags(color)
if part2memo[color] then return part2memo[color] end
local total = 0
for sub_color, count in pairs(contains[color]) do
-- Count the bag itself and all the bags it contains
total = total + count * (count_bags(sub_color) + 1)
end
part2memo[color] = total
return total
end
print(count_bags("shiny gold"))

View File

@ -12,9 +12,9 @@ My solutions to the Advent of Code puzzles.
4 ██ ██ ██ ██
5 ██ ██ ██ ██
6 ██ ██ ██
7 ██ ██
7 ██ ██ ██
8 ██ ██
9 ██
9 ██
10 ██ ██
11 ██ ██
12 ██ ██