[Python/2016] Move solutions into .py files

This commit is contained in:
Felix Bargfeldt 2023-10-29 12:38:12 +01:00
parent 0269ad8fc3
commit 2514b1d11f
Signed by: Defelo
GPG key ID: 2A05272471204DD3
50 changed files with 1172 additions and 3386 deletions

View file

@ -1,135 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 01"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 1\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"353"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x = y = 0\n",
"dx, dy = 1, 0\n",
"for e in puzzle.split(\", \"):\n",
" l = int(e[1:])\n",
" if e[0] == \"L\":\n",
" dx, dy = dy, -dx\n",
" else:\n",
" dx, dy = -dy, dx\n",
" x += l * dx\n",
" y += l * dy\n",
"abs(x) + abs(y)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"152"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x = y = 0\n",
"dx, dy = 1, 0\n",
"seen = {(0, 0)}\n",
"for e in puzzle.split(\", \"):\n",
" l = int(e[1:])\n",
" if e[0] == \"L\":\n",
" dx, dy = dy, -dx\n",
" else:\n",
" dx, dy = -dy, dx\n",
" for i in range(l):\n",
" x += dx\n",
" y += dy\n",
" if (x, y) in seen:\n",
" break\n",
" seen.add((x, y))\n",
" else:\n",
" continue\n",
" break\n",
"abs(x) + abs(y)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

39
Python/2016/01.py Normal file
View file

@ -0,0 +1,39 @@
from lib import *
input = read_input(2016, 1)
x = y = 0
dx, dy = 1, 0
for e in input.split(", "):
l = int(e[1:])
if e[0] == "L":
dx, dy = dy, -dx
else:
dx, dy = -dy, dx
x += l * dx
y += l * dy
print(abs(x) + abs(y))
x = y = 0
dx, dy = 1, 0
seen = {(0, 0)}
for e in input.split(", "):
l = int(e[1:])
if e[0] == "L":
dx, dy = dy, -dx
else:
dx, dy = -dy, dx
for i in range(l):
x += dx
y += dy
if (x, y) in seen:
print(abs(x) + abs(y))
break
seen.add((x, y))
else:
continue
break

View file

@ -1,129 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 02"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 2\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"12578\n"
]
}
],
"source": [
"out = []\n",
"x = y = 1\n",
"for line in puzzle.splitlines():\n",
" for c in line:\n",
" if c == \"L\" and x > 0: x -= 1\n",
" elif c == \"R\" and x < 2: x += 1\n",
" elif c == \"U\" and y > 0: y -= 1\n",
" elif c == \"D\" and y < 2: y += 1\n",
" out.append(y * 3 + x + 1)\n",
"print(*out, sep=\"\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"516DD\n"
]
}
],
"source": [
"out = \"\"\n",
"x, y = 0, 2\n",
"keypad = [\n",
" \" 1 \",\n",
" \" 234 \",\n",
" \"56789\",\n",
" \" ABC \",\n",
" \" D \",\n",
"]\n",
"for line in puzzle.splitlines():\n",
" for c in line:\n",
" nx, ny = x, y\n",
" if c == \"L\": nx -= 1\n",
" elif c == \"R\": nx += 1\n",
" elif c == \"U\": ny -= 1\n",
" elif c == \"D\": ny += 1\n",
" if 0 <= nx < 5 and 0 <= ny < 5 and keypad[ny][nx] != \" \":\n",
" x, y = nx, ny\n",
" out += keypad[y][x]\n",
"print(out)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

50
Python/2016/02.py Normal file
View file

@ -0,0 +1,50 @@
from lib import *
input = read_input(2016, 2)
out = []
x = y = 1
for line in input.splitlines():
for c in line:
if c == "L" and x > 0:
x -= 1
elif c == "R" and x < 2:
x += 1
elif c == "U" and y > 0:
y -= 1
elif c == "D" and y < 2:
y += 1
out.append(y * 3 + x + 1)
print(*out, sep="")
out = ""
x, y = 0, 2
keypad = [" 1 ", " 234 ", "56789", " ABC ", " D "]
for line in input.splitlines():
for c in line:
nx, ny = x, y
if c == "L":
nx -= 1
elif c == "R":
nx += 1
elif c == "U":
ny -= 1
elif c == "D":
ny += 1
if 0 <= nx < 5 and 0 <= ny < 5 and keypad[ny][nx] != " ":
x, y = nx, ny
out += keypad[y][x]
print(out)

View file

@ -1,112 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 03"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 3\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1050"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sum((y:=sorted(map(int, x)))[2] < y[0]+y[1] for x in map(str.split, puzzle.splitlines()))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1921"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"triangles = [int(b) for a in zip(*map(str.split, puzzle.splitlines())) for b in a]\n",
"out = 0\n",
"while triangles:\n",
" a, b, c = sorted([triangles.pop(0) for _ in 'xxx'])\n",
" out += c < a + b\n",
"out"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

13
Python/2016/03.py Normal file
View file

@ -0,0 +1,13 @@
from lib import *
input = read_input(2016, 3)
print(sum((y := sorted(map(int, x)))[2] < y[0] + y[1] for x in map(str.split, input.splitlines())))
triangles = [int(b) for a in zip(*map(str.split, input.splitlines())) for b in a]
out = 0
while triangles:
a, b, c = sorted([triangles.pop(0) for _ in "xxx"])
out += c < a + b
print(out)

View file

@ -1,116 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 04"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 4\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"173787"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from collections import Counter\n",
"import re\n",
"\n",
"out = 0\n",
"for room in puzzle.splitlines():\n",
" name, sector, checksum = re.match(r\"^([a-z\\-]+)-(\\d+)\\[([a-z]+)\\]$\", room).groups()\n",
" if [*checksum] == [a[0] for a in sorted(Counter(name.replace(\"-\", \"\")).items(), key=lambda a: (-a[1], a[0]))[:5]]:\n",
" out += int(sector)\n",
"out"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"548\n"
]
}
],
"source": [
"for room in puzzle.splitlines():\n",
" name, sector = re.match(r\"^([a-z\\-]+)-(\\d+)\\[[a-z]+\\]$\", room).groups()\n",
" name = \"\".join(chr((ord(c) - 0x61 + int(sector)) % 26 + 0x61) if c != \"-\" else \" \" for c in name)\n",
" if \"north\" in name:\n",
" print(sector)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

22
Python/2016/04.py Normal file
View file

@ -0,0 +1,22 @@
from lib import *
input = read_input(2016, 4)
out = 0
for room in input.splitlines():
name, sector, checksum = re.match(r"^([a-z\-]+)-(\d+)\[([a-z]+)\]$", room).groups()
if [*checksum] == [a[0] for a in sorted(Counter(name.replace("-", "")).items(), key=lambda a: (-a[1], a[0]))[:5]]:
out += int(sector)
print(out)
for room in input.splitlines():
name, sector = re.match(r"^([a-z\-]+)-(\d+)\[[a-z]+\]$", room).groups()
name = "".join(chr((ord(c) - 0x61 + int(sector)) % 26 + 0x61) if c != "-" else " " for c in name)
if "north" in name:
print(sector)
break

View file

@ -1,119 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 05"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 5\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"d4cd2ee1\n"
]
}
],
"source": [
"from hashlib import md5\n",
"\n",
"out = \"\"\n",
"i = 0\n",
"while len(out) < 8:\n",
" while not (digest:=md5(f\"{puzzle}{i}\".encode()).hexdigest()).startswith(\"0\"*5):\n",
" i += 1\n",
" out += digest[5]\n",
" i += 1\n",
"print(out)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"f2c730e5\n"
]
}
],
"source": [
"out = [\"_\"] * 8\n",
"i = 0\n",
"while \"_\" in out:\n",
" while not (digest:=md5(f\"{puzzle}{i}\".encode()).hexdigest()).startswith(\"0\"*5):\n",
" i += 1\n",
" i += 1\n",
" if not \"0\" <= digest[5] <= \"7\" or out[(d:=int(digest[5]))] != \"_\":\n",
" continue\n",
" out[d] = digest[6]\n",
"print(\"\".join(out))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

27
Python/2016/05.py Normal file
View file

@ -0,0 +1,27 @@
from lib import *
input = read_input(2016, 5)
out = ""
i = 0
while len(out) < 8:
while not (digest := hashlib.md5(f"{input.strip()}{i}".encode()).hexdigest()).startswith("0" * 5):
i += 1
out += digest[5]
i += 1
print(out)
out = ["_"] * 8
i = 0
while "_" in out:
while not (digest := hashlib.md5(f"{input.strip()}{i}".encode()).hexdigest()).startswith("0" * 5):
i += 1
i += 1
if not "0" <= digest[5] <= "7" or out[(d := int(digest[5]))] != "_":
continue
out[d] = digest[6]
print("".join(out))

View file

@ -1,103 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 06"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 6\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"tsreykjj\n"
]
}
],
"source": [
"from collections import Counter\n",
"\n",
"print(\"\".join([Counter(x).most_common(1)[0][0] for x in zip(*puzzle.splitlines())]))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"hnfbujie\n"
]
}
],
"source": [
"print(\"\".join([Counter(x).most_common()[-1][0] for x in zip(*puzzle.splitlines())]))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

6
Python/2016/06.py Normal file
View file

@ -0,0 +1,6 @@
from lib import *
input = read_input(2016, 6)
print("".join([Counter(x).most_common(1)[0][0] for x in zip(*input.splitlines())]))
print("".join([Counter(x).most_common()[-1][0] for x in zip(*input.splitlines())]))

View file

@ -1,155 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 07"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 7\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"105"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def check(ip):\n",
" tmp = \"\"\n",
" c = 0\n",
" ok = False\n",
" for x in ip:\n",
" tmp += x\n",
" if x == \"[\":\n",
" c += 1\n",
" tmp = \"\"\n",
" elif x == \"]\":\n",
" c -= 1\n",
" tmp = \"\"\n",
" elif len(tmp) >= 4:\n",
" if tmp[-1] == tmp[-4] and tmp[-2] == tmp[-3] and tmp[-1] != tmp[-2]:\n",
" if c:\n",
" return False\n",
" ok = True\n",
" return ok\n",
"\n",
"sum(check(line) for line in puzzle.splitlines())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"258"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def check(ip):\n",
" supernet = []\n",
" hypernet = []\n",
" tmp = \"\"\n",
" c = 0\n",
" for x in ip:\n",
" k = tmp\n",
" tmp += x\n",
" if x == \"[\":\n",
" if k:\n",
" [hypernet, supernet][not c].append(k)\n",
" c += 1\n",
" tmp = \"\"\n",
" elif x == \"]\":\n",
" if k:\n",
" [hypernet, supernet][not c].append(k)\n",
" c -= 1\n",
" tmp = \"\"\n",
" if tmp:\n",
" [hypernet, supernet][not c].append(tmp)\n",
" \n",
" for sup in supernet:\n",
" for i in range(len(sup) - 2):\n",
" if sup[i] != sup[i + 2] or sup[i] == sup[i + 1]:\n",
" continue\n",
" if any(sup[i+1]+sup[i]+sup[i+1] in hyp for hyp in hypernet):\n",
" return True\n",
" return False\n",
"\n",
"sum(check(line) for line in puzzle.splitlines())"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

59
Python/2016/07.py Normal file
View file

@ -0,0 +1,59 @@
from lib import *
input = read_input(2016, 7)
def check(ip):
tmp = ""
c = 0
ok = False
for x in ip:
tmp += x
if x == "[":
c += 1
tmp = ""
elif x == "]":
c -= 1
tmp = ""
elif len(tmp) >= 4:
if tmp[-1] == tmp[-4] and tmp[-2] == tmp[-3] and tmp[-1] != tmp[-2]:
if c:
return False
ok = True
return ok
print(sum(check(line) for line in input.splitlines()))
def check(ip):
supernet = []
hypernet = []
tmp = ""
c = 0
for x in ip:
k = tmp
tmp += x
if x == "[":
if k:
[hypernet, supernet][not c].append(k)
c += 1
tmp = ""
elif x == "]":
if k:
[hypernet, supernet][not c].append(k)
c -= 1
tmp = ""
if tmp:
[hypernet, supernet][not c].append(tmp)
for sup in supernet:
for i in range(len(sup) - 2):
if sup[i] != sup[i + 2] or sup[i] == sup[i + 1]:
continue
if any(sup[i + 1] + sup[i] + sup[i + 1] in hyp for hyp in hypernet):
return True
return False
print(sum(check(line) for line in input.splitlines()))

View file

@ -1,130 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 08"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 8\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"121"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import re\n",
"\n",
"T = lambda g: [*map(list, zip(*g))]\n",
"def rotate(g, a, b):\n",
" g[a] = [g[a][(i - b) % len(g[a])] for i in range(len(g[a]))]\n",
" return g\n",
"\n",
"grid = [[0 for _ in range(50)] for _ in range(6)]\n",
"for line in puzzle.splitlines():\n",
" if match := re.match(r\"^rect (\\d+)x(\\d+)$\", line):\n",
" w, h = map(int, match.groups())\n",
" for i in range(h):\n",
" for j in range(w):\n",
" grid[i][j] = 1\n",
" elif match := re.match(r\"^rotate row y=(\\d+) by (\\d+)$\", line):\n",
" a, b = map(int, match.groups())\n",
" rotate(grid, a, b)\n",
" elif match := re.match(r\"^rotate column x=(\\d+) by (\\d+)$\", line):\n",
" a, b = map(int, match.groups())\n",
" grid = T(rotate(T(grid), a, b))\n",
"sum(map(sum, grid))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"###### ## ## ###### ## ## #### ######## #### ######## ###### ## \n",
"## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## \n",
"## ## ## ## ## ## ## ## ## ###### ## ## ###### ## ## \n",
"###### ## ## ###### ## ## ## ## ## ## ## ## ## \n",
"## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## \n",
"## ## #### ## ## #### #### ######## #### ######## ###### ######## \n"
]
}
],
"source": [
"for line in grid:\n",
" print(\"\".join(\" #\"[c]*2 for c in line))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

36
Python/2016/08.py Normal file
View file

@ -0,0 +1,36 @@
from lib import *
input = read_input(2016, 8)
T = lambda g: [*map(list, zip(*g))]
def rotate(g, a, b):
g[a] = [g[a][(i - b) % len(g[a])] for i in range(len(g[a]))]
return g
grid = [[0 for _ in range(50)] for _ in range(6)]
for line in input.splitlines():
if match := re.match(r"^rect (\d+)x(\d+)$", line):
w, h = map(int, match.groups())
for i in range(h):
for j in range(w):
grid[i][j] = 1
elif match := re.match(r"^rotate row y=(\d+) by (\d+)$", line):
a, b = map(int, match.groups())
rotate(grid, a, b)
elif match := re.match(r"^rotate column x=(\d+) by (\d+)$", line):
a, b = map(int, match.groups())
grid = T(rotate(T(grid), a, b))
print(sum(map(sum, grid)))
for line in grid:
print("".join(" #"[c] * 2 for c in line))

View file

@ -1,136 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 09"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 9\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"110346"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"out = 0\n",
"i = 0\n",
"while i < len(puzzle):\n",
" if puzzle[i] == \"(\":\n",
" x = puzzle[i+1:].split(\")\")[0]\n",
" a, b = map(int, x.split(\"x\"))\n",
" i += len(x) + 2\n",
" out += b * min(a, len(puzzle) - i)\n",
" i += a\n",
" continue\n",
" \n",
" out += 1\n",
" i += 1\n",
"out"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"10774309173"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve(inp):\n",
" out = 0\n",
" i = 0\n",
" while i < len(inp):\n",
" if inp[i] == \"(\":\n",
" x = inp[i+1:].split(\")\")[0]\n",
" a, b = map(int, x.split(\"x\"))\n",
" i += len(x) + 2\n",
" out += b * solve(inp[i:i+a])\n",
" i += a\n",
" continue\n",
" \n",
" out += 1\n",
" i += 1\n",
" return out\n",
"\n",
"solve(puzzle)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

37
Python/2016/09.py Normal file
View file

@ -0,0 +1,37 @@
from lib import *
input = read_input(2016, 9).strip()
out = 0
i = 0
while i < len(input):
if input[i] == "(":
x = input[i + 1 :].split(")")[0]
a, b = map(int, x.split("x"))
i += len(x) + 2
out += b * min(a, len(input) - i)
i += a
continue
out += 1
i += 1
print(out)
def solve(inp):
out = 0
i = 0
while i < len(inp):
if inp[i] == "(":
x = inp[i + 1 :].split(")")[0]
a, b = map(int, x.split("x"))
i += len(x) + 2
out += b * solve(inp[i : i + a])
i += a
continue
out += 1
i += 1
return out
print(solve(input))

View file

@ -1,162 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 10"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 10\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"56\n"
]
}
],
"source": [
"values = {}\n",
"fw = {}\n",
"for line in map(str.split, puzzle.splitlines()):\n",
" if line[0] == \"bot\":\n",
" src, dst1, dst2 = map(int, [line[1], line[6], line[11]])\n",
" fw[src] = [dst1, dst2]\n",
" else:\n",
" val, dst = map(int, [line[1], line[5]])\n",
" values.setdefault(dst, []).append(val)\n",
"\n",
"queue = []\n",
"for k, v in values.items():\n",
" if len(v) == 2:\n",
" queue.append((k, *sorted(v)))\n",
"\n",
"while queue:\n",
" p, l, h = queue.pop()\n",
" \n",
" if (l, h) == (17, 61):\n",
" print(p)\n",
" break\n",
" \n",
" values.setdefault(fw[p][0], []).append(l)\n",
" values.setdefault(fw[p][1], []).append(h)\n",
"\n",
" for k in fw[p]:\n",
" v = values[k]\n",
" if len(v) == 2:\n",
" queue.append((k, *sorted(v)))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"7847"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"values = {}\n",
"fw = {}\n",
"out = {}\n",
"for line in map(str.split, puzzle.splitlines()):\n",
" if line[0] == \"bot\":\n",
" src, dst1, dst2 = map(int, [line[1], line[6], line[11]])\n",
" fw[src] = [(dst1, line[5]==\"output\"), (dst2, line[10]==\"output\")]\n",
" else:\n",
" val, dst = map(int, [line[1], line[5]])\n",
" [values, out][line[4] == \"output\"].setdefault(dst, []).append(val)\n",
"\n",
"queue = []\n",
"for k, v in values.items():\n",
" if len(v) == 2:\n",
" queue.append((k, *sorted(v)))\n",
"\n",
"while queue:\n",
" p, l, h = queue.pop()\n",
" \n",
" for val, (k, o) in zip([l, h], fw[p]):\n",
" if o:\n",
" out[k] = val\n",
" continue\n",
" \n",
" values.setdefault(k, []).append(val)\n",
"\n",
" v = values[k]\n",
" if len(v) == 2:\n",
" queue.append((k, *sorted(v)))\n",
"\n",
"out[0] * out[1] * out[2]"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

65
Python/2016/10.py Normal file
View file

@ -0,0 +1,65 @@
from lib import *
input = read_input(2016, 10)
values = {}
fw = {}
for line in map(str.split, input.splitlines()):
if line[0] == "bot":
src, dst1, dst2 = map(int, [line[1], line[6], line[11]])
fw[src] = [dst1, dst2]
else:
val, dst = map(int, [line[1], line[5]])
values.setdefault(dst, []).append(val)
queue = []
for k, v in values.items():
if len(v) == 2:
queue.append((k, *sorted(v)))
while queue:
p, l, h = queue.pop()
if (l, h) == (17, 61):
print(p)
break
values.setdefault(fw[p][0], []).append(l)
values.setdefault(fw[p][1], []).append(h)
for k in fw[p]:
v = values[k]
if len(v) == 2:
queue.append((k, *sorted(v)))
values = {}
fw = {}
out = {}
for line in map(str.split, input.splitlines()):
if line[0] == "bot":
src, dst1, dst2 = map(int, [line[1], line[6], line[11]])
fw[src] = [(dst1, line[5] == "output"), (dst2, line[10] == "output")]
else:
val, dst = map(int, [line[1], line[5]])
[values, out][line[4] == "output"].setdefault(dst, []).append(val)
queue = []
for k, v in values.items():
if len(v) == 2:
queue.append((k, *sorted(v)))
while queue:
p, l, h = queue.pop()
for val, (k, o) in zip([l, h], fw[p]):
if o:
out[k] = val
continue
values.setdefault(k, []).append(val)
v = values[k]
if len(v) == 2:
queue.append((k, *sorted(v)))
print(out[0] * out[1] * out[2])

View file

@ -1,183 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 11"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 11\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"33"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import re\n",
"\n",
"names = {}\n",
"get_id = lambda name: names.setdefault(name, len(names))\n",
"generators = {}\n",
"microchips = {}\n",
"for i, line in enumerate(puzzle.splitlines()):\n",
" for g in map(get_id, re.findall(r\"([a-z]+) generator\", line)):\n",
" generators[g] = i\n",
" for m in map(get_id, re.findall(r\"([a-z]+)-compatible microchip\", line)):\n",
" microchips[m] = i\n",
"generators = tuple([generators[i] for i in range(len(generators))])\n",
"microchips = tuple([microchips[i] for i in range(len(microchips))])\n",
"\n",
"sub = lambda lst, i, x: lst[:i] + (x,) + lst[i+1:]\n",
"\n",
"def is_valid(generators, microchips):\n",
" for i, e in enumerate(microchips):\n",
" if not 0 <= e < 4:\n",
" return False\n",
" if generators[i] == e:\n",
" continue\n",
" if e in generators:\n",
" return False\n",
" return True\n",
"\n",
"def solve():\n",
" def add_to_queue(d, e, g, m):\n",
" g, m = map(tuple, zip(*sorted(zip(g, m))))\n",
" if is_valid(g, m):\n",
" queue.append((d, e, g, m))\n",
"\n",
" queue = [(0, 0, generators, microchips)]\n",
" visited = set()\n",
" while queue:\n",
" dist, el, ge, mi = queue.pop(0)\n",
"\n",
" if (el, ge, mi) in visited:\n",
" continue\n",
" visited.add((el, ge, mi))\n",
"\n",
" if ge == mi == (3,) * len(ge):\n",
" return dist\n",
"\n",
" for d in [-1, 1]:\n",
" if not 0 <= (e := el + d) < 4:\n",
" continue\n",
" if d == -1 and all(x >= el for x in ge + mi):\n",
" continue\n",
"\n",
" for i in range(len(ge)):\n",
" if ge[i] == el:\n",
" add_to_queue(dist + 1, e, sub(ge, i, e), mi)\n",
" if mi[i] == el:\n",
" add_to_queue(dist + 1, e, ge, sub(mi, i, e))\n",
" if ge[i] == mi[i] == el:\n",
" add_to_queue(dist + 1, e, sub(ge, i, e), sub(mi, i, e))\n",
" for j in range(i + 1, len(ge)):\n",
" if ge[i] == ge[j] == el:\n",
" add_to_queue(dist + 1, e, sub(sub(ge, j, e), i, e), mi)\n",
" if mi[i] == mi[j] == el:\n",
" add_to_queue(dist + 1, e, ge, sub(sub(mi, j, e), i, e))\n",
"\n",
"solve()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"57"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"names = {}\n",
"generators = {}\n",
"microchips = {}\n",
"for i, line in enumerate(puzzle.splitlines()):\n",
" for g in map(get_id, re.findall(r\"([a-z]+) generator\", line)):\n",
" generators[g] = i\n",
" for m in map(get_id, re.findall(r\"([a-z]+)-compatible microchip\", line)):\n",
" microchips[m] = i\n",
"for i in map(get_id, \"ab\"):\n",
" generators[i] = microchips[i] = 0\n",
"generators = tuple([generators[i] for i in range(len(generators))])\n",
"microchips = tuple([microchips[i] for i in range(len(microchips))])\n",
"\n",
"solve()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

96
Python/2016/11.py Normal file
View file

@ -0,0 +1,96 @@
from lib import *
input = read_input(2016, 11)
names = {}
get_id = lambda name: names.setdefault(name, len(names))
generators = {}
microchips = {}
for i, line in enumerate(input.splitlines()):
for g in map(get_id, re.findall(r"([a-z]+) generator", line)):
generators[g] = i
for m in map(get_id, re.findall(r"([a-z]+)-compatible microchip", line)):
microchips[m] = i
generators = tuple([generators[i] for i in range(len(generators))])
microchips = tuple([microchips[i] for i in range(len(microchips))])
sub = lambda lst, i, x: lst[:i] + (x,) + lst[i + 1 :]
def is_valid(generators, microchips):
for i, e in enumerate(microchips):
if not 0 <= e < 4:
return False
if generators[i] == e:
continue
if e in generators:
return False
return True
def solve():
def add_to_queue(d, e, g, m):
g, m = map(tuple, zip(*sorted(zip(g, m))))
if is_valid(g, m):
queue.append((d, e, g, m))
queue = [(0, 0, generators, microchips)]
visited = set()
while queue:
dist, el, ge, mi = queue.pop(0)
if (el, ge, mi) in visited:
continue
visited.add((el, ge, mi))
if ge == mi == (3,) * len(ge):
return dist
for d in [-1, 1]:
if not 0 <= (e := el + d) < 4:
continue
if d == -1 and all(x >= el for x in ge + mi):
continue
for i in range(len(ge)):
if ge[i] == el:
add_to_queue(dist + 1, e, sub(ge, i, e), mi)
if mi[i] == el:
add_to_queue(dist + 1, e, ge, sub(mi, i, e))
if ge[i] == mi[i] == el:
add_to_queue(dist + 1, e, sub(ge, i, e), sub(mi, i, e))
for j in range(i + 1, len(ge)):
if ge[i] == ge[j] == el:
add_to_queue(dist + 1, e, sub(sub(ge, j, e), i, e), mi)
if mi[i] == mi[j] == el:
add_to_queue(dist + 1, e, ge, sub(sub(mi, j, e), i, e))
print(solve())
names = {}
generators = {}
microchips = {}
for i, line in enumerate(input.splitlines()):
for g in map(get_id, re.findall(r"([a-z]+) generator", line)):
generators[g] = i
for m in map(get_id, re.findall(r"([a-z]+)-compatible microchip", line)):
microchips[m] = i
for i in map(get_id, "ab"):
generators[i] = microchips[i] = 0
generators = tuple([generators[i] for i in range(len(generators))])
microchips = tuple([microchips[i] for i in range(len(microchips))])
print(solve())

View file

@ -1,133 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 12"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 12\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"318007"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"program = puzzle.splitlines()\n",
"registers = {k: 0 for k in \"abcd\"}\n",
"\n",
"def simulate():\n",
" pc = 0\n",
" while pc < len(program):\n",
" cmd, *args = program[pc].split()\n",
" x = registers[args[0]] if args[0] in registers else int(args[0])\n",
" if cmd == \"cpy\":\n",
" registers[args[1]] = x\n",
" pc += 1\n",
" elif cmd == \"inc\":\n",
" registers[args[0]] += 1\n",
" pc += 1\n",
" elif cmd == \"dec\":\n",
" registers[args[0]] -= 1\n",
" pc += 1\n",
" elif cmd == \"jnz\":\n",
" if x:\n",
" pc += int(args[1])\n",
" else:\n",
" pc += 1\n",
" return registers[\"a\"]\n",
"\n",
"simulate()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"9227661"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"registers = {k: 0 for k in \"abcd\"}\n",
"registers[\"c\"] = 1\n",
"simulate()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

37
Python/2016/12.py Normal file
View file

@ -0,0 +1,37 @@
from lib import *
input = read_input(2016, 12)
program = input.splitlines()
registers = {k: 0 for k in "abcd"}
def simulate():
pc = 0
while pc < len(program):
cmd, *args = program[pc].split()
x = registers[args[0]] if args[0] in registers else int(args[0])
if cmd == "cpy":
registers[args[1]] = x
pc += 1
elif cmd == "inc":
registers[args[0]] += 1
pc += 1
elif cmd == "dec":
registers[args[0]] -= 1
pc += 1
elif cmd == "jnz":
if x:
pc += int(args[1])
else:
pc += 1
return registers["a"]
print(simulate())
registers = {k: 0 for k in "abcd"}
registers["c"] = 1
print(simulate())

View file

@ -1,141 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 13"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 13\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"96\n"
]
}
],
"source": [
"num = int(puzzle)\n",
"wall = lambda x, y: bin(x*x + 3*x + 2*x*y + y + y*y + num).count(\"1\") % 2\n",
"\n",
"q = [(0, 1, 1)]\n",
"visited = set()\n",
"while q:\n",
" d, x, y = q.pop(0)\n",
" \n",
" if (x, y) in visited:\n",
" continue\n",
" visited.add((x, y))\n",
" \n",
" if (x, y) == (31, 39):\n",
" print(d)\n",
" break\n",
" \n",
" for nx, ny in [(x-1,y),(x+1,y),(x,y-1),(x,y+1)]:\n",
" if nx < 0 or ny < 0 or wall(nx, ny):\n",
" continue\n",
" q.append((d + 1, nx, ny))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"141"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"q = [(0, 1, 1)]\n",
"visited = set()\n",
"count = 0\n",
"while q:\n",
" d, x, y = q.pop(0)\n",
" \n",
" if (x, y) in visited:\n",
" continue\n",
" visited.add((x, y))\n",
"\n",
" if d > 50:\n",
" break\n",
" count += 1\n",
" \n",
" for nx, ny in [(x-1,y),(x+1,y),(x,y-1),(x,y+1)]:\n",
" if nx < 0 or ny < 0 or wall(nx, ny):\n",
" continue\n",
" q.append((d + 1, nx, ny))\n",
"count"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

39
Python/2016/13.py Normal file
View file

@ -0,0 +1,39 @@
from lib import *
input = read_input(2016, 13)
num = int(input)
wall = lambda x, y: bin(x * x + 3 * x + 2 * x * y + y + y * y + num).count("1") % 2
q = [(0, 1, 1)]
visited = set()
while q:
d, x, y = q.pop(0)
if (x, y) in visited:
continue
visited.add((x, y))
if (x, y) == (31, 39):
print(d)
break
for nx, ny in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
if nx < 0 or ny < 0 or wall(nx, ny):
continue
q.append((d + 1, nx, ny))
q = [(0, 1, 1)]
visited = set()
count = 0
while q:
d, x, y = q.pop(0)
if (x, y) in visited:
continue
visited.add((x, y))
if d > 50:
break
count += 1
for nx, ny in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
if nx < 0 or ny < 0 or wall(nx, ny):
continue
q.append((d + 1, nx, ny))
print(count)

View file

@ -1,152 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 14"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 14\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"25427\n"
]
}
],
"source": [
"import hashlib\n",
"import re\n",
"\n",
"def hash(idx):\n",
" return hashlib.md5(f\"{puzzle}{idx}\".encode()).hexdigest()\n",
"\n",
"def first(idx):\n",
" if match := re.match(r\"^.*?((.)\\2{2}).*$\", hash(idx)):\n",
" return match.group(2)\n",
"\n",
"def second(idx, m):\n",
" for i in range(1, 1001):\n",
" if m * 5 in hash(idx + i):\n",
" return True\n",
" return False\n",
"\n",
"idx = 0\n",
"cnt = 0\n",
"while True:\n",
" if (x := first(idx)) and second(idx, x):\n",
" cnt += 1\n",
" if cnt == 64:\n",
" break\n",
" idx += 1\n",
"print(idx)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"22045\n"
]
}
],
"source": [
"dp = {}\n",
"def hash(idx):\n",
" if idx in dp: return dp[idx]\n",
" out = hashlib.md5(f\"{puzzle}{idx}\".encode()).hexdigest()\n",
" for _ in range(2016):\n",
" out = hashlib.md5(out.encode()).hexdigest()\n",
" dp[idx] = out\n",
" return out\n",
"\n",
"def first(idx):\n",
" if match := re.match(r\"^.*?((.)\\2{2}).*$\", hash(idx)):\n",
" return match.group(2)\n",
"\n",
"def second(idx, m):\n",
" for i in range(1, 1001):\n",
" if m * 5 in hash(idx + i):\n",
" return True\n",
" return False\n",
"\n",
"idx = 0\n",
"cnt = 0\n",
"while True:\n",
" if (x := first(idx)) and second(idx, x):\n",
" cnt += 1\n",
" if cnt == 64:\n",
" break\n",
" idx += 1\n",
"print(idx)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

74
Python/2016/14.py Normal file
View file

@ -0,0 +1,74 @@
from lib import *
input = read_input(2016, 14).strip()
def hash(idx):
return hashlib.md5(f"{input}{idx}".encode()).hexdigest()
def first(idx):
if match := re.match(r"^.*?((.)\2{2}).*$", hash(idx)):
return match.group(2)
def second(idx, m):
for i in range(1, 1001):
if m * 5 in hash(idx + i):
return True
return False
idx = 0
cnt = 0
while True:
if (x := first(idx)) and second(idx, x):
cnt += 1
if cnt == 64:
break
idx += 1
print(idx)
dp = {}
def hash(idx):
if idx in dp:
return dp[idx]
out = hashlib.md5(f"{input}{idx}".encode()).hexdigest()
for _ in range(2016):
out = hashlib.md5(out.encode()).hexdigest()
dp[idx] = out
return out
def first(idx):
if match := re.match(r"^.*?((.)\2{2}).*$", hash(idx)):
return match.group(2)
def second(idx, m):
for i in range(1, 1001):
if m * 5 in hash(idx + i):
return True
return False
idx = 0
cnt = 0
while True:
if (x := first(idx)) and second(idx, x):
cnt += 1
if cnt == 64:
break
idx += 1
print(idx)

View file

@ -1,119 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 15"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 15\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"203660\n"
]
}
],
"source": [
"discs = []\n",
"for line in puzzle.splitlines():\n",
" words = line.split()\n",
" discs.append((int(words[3]), int(words[-1][:-1])))\n",
"\n",
"def test(t):\n",
" return all((t + x + i + 1) % n == 0 for i, (n, x) in enumerate(discs))\n",
"\n",
"t = 0\n",
"while not test(t): t+=1\n",
"print(t)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2408135\n"
]
}
],
"source": [
"discs = []\n",
"for line in puzzle.splitlines():\n",
" words = line.split()\n",
" discs.append((int(words[3]), int(words[-1][:-1])))\n",
"discs.append((11, 0))\n",
"\n",
"t = 0\n",
"while not test(t): t+=1\n",
"print(t)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

35
Python/2016/15.py Normal file
View file

@ -0,0 +1,35 @@
from lib import *
input = read_input(2016, 15)
discs = []
for line in input.splitlines():
words = line.split()
discs.append((int(words[3]), int(words[-1][:-1])))
def test(t):
return all((t + x + i + 1) % n == 0 for i, (n, x) in enumerate(discs))
t = 0
while not test(t):
t += 1
print(t)
discs = []
for line in input.splitlines():
words = line.split()
discs.append((int(words[3]), int(words[-1][:-1])))
discs.append((11, 0))
t = 0
while not test(t):
t += 1
print(t)

View file

@ -1,120 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 16"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 16\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'10010101010011101'"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def fill(state, n):\n",
" while len(state) < n:\n",
" state = state + \"0\" + \"\".join(\"10\"[c==\"1\"] for c in reversed(state))\n",
" \n",
" return state[:n]\n",
"\n",
"def checksum(inp):\n",
" if len(inp) % 2: return inp\n",
" out = \"\"\n",
" for i in range(0, len(inp), 2):\n",
" out += \"01\"[inp[i]==inp[i+1]]\n",
" return checksum(out)\n",
"\n",
"checksum(fill(puzzle, 272))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'01100111101101111'"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"checksum(fill(puzzle, 35651584))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

26
Python/2016/16.py Normal file
View file

@ -0,0 +1,26 @@
from lib import *
input = read_input(2016, 16).strip()
def fill(state, n):
while len(state) < n:
state = state + "0" + "".join("10"[c == "1"] for c in reversed(state))
return state[:n]
def checksum(inp):
if len(inp) % 2:
return inp
out = ""
for i in range(0, len(inp), 2):
out += "01"[inp[i] == inp[i + 1]]
return checksum(out)
print(checksum(fill(input, 272)))
print(checksum(fill(input, 35651584)))

View file

@ -1,151 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 17"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 17\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'RLDUDRDDRR'"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import hashlib\n",
"\n",
"def get_state(path):\n",
" digest = hashlib.md5((puzzle + path).encode()).hexdigest()\n",
" return [c >= \"b\" for c in digest[:4]] # up, down, left, right\n",
"\n",
"def find_path():\n",
" queue = [(\"\", 0, 0)]\n",
" while True:\n",
" path, x, y = queue.pop(0)\n",
" if x == y == 3:\n",
" return path\n",
" \n",
" up, down, left, right = get_state(path)\n",
" if up and y > 0:\n",
" queue.append((path + \"U\", x, y - 1))\n",
" if down and y < 3:\n",
" queue.append((path + \"D\", x, y + 1))\n",
" if left and x > 0:\n",
" queue.append((path + \"L\", x - 1, y))\n",
" if right and x < 3:\n",
" queue.append((path + \"R\", x + 1, y))\n",
"\n",
"find_path()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"590"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def find_path():\n",
" queue = [(\"\", 0, 0)]\n",
" longest = \"\"\n",
" while queue:\n",
" path, x, y = queue.pop(0)\n",
" if x == y == 3:\n",
" if len(path) > len(longest): longest = path\n",
" continue\n",
" \n",
" up, down, left, right = get_state(path)\n",
" if up and y > 0:\n",
" queue.append((path + \"U\", x, y - 1))\n",
" if down and y < 3:\n",
" queue.append((path + \"D\", x, y + 1))\n",
" if left and x > 0:\n",
" queue.append((path + \"L\", x - 1, y))\n",
" if right and x < 3:\n",
" queue.append((path + \"R\", x + 1, y))\n",
" \n",
" return longest\n",
"\n",
"len(find_path())"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

68
Python/2016/17.py Normal file
View file

@ -0,0 +1,68 @@
from lib import *
input = read_input(2016, 17).strip()
def get_state(path):
digest = hashlib.md5((input + path).encode()).hexdigest()
return [c >= "b" for c in digest[:4]] # up, down, left, right
def find_path():
queue = [("", 0, 0)]
while True:
path, x, y = queue.pop(0)
if x == y == 3:
return path
up, down, left, right = get_state(path)
if up and y > 0:
queue.append((path + "U", x, y - 1))
if down and y < 3:
queue.append((path + "D", x, y + 1))
if left and x > 0:
queue.append((path + "L", x - 1, y))
if right and x < 3:
queue.append((path + "R", x + 1, y))
print(find_path())
def find_path():
queue = [("", 0, 0)]
longest = ""
while queue:
path, x, y = queue.pop(0)
if x == y == 3:
if len(path) > len(longest):
longest = path
continue
up, down, left, right = get_state(path)
if up and y > 0:
queue.append((path + "U", x, y - 1))
if down and y < 3:
queue.append((path + "D", x, y + 1))
if left and x > 0:
queue.append((path + "L", x - 1, y))
if right and x < 3:
queue.append((path + "R", x + 1, y))
return longest
print(len(find_path()))

View file

@ -1,123 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 18"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 18\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2013"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def next_row(row):\n",
" return \"\".join(\".^\"[a!=b] for a, b in zip(\".\" + row[:-1], row[1:] + \".\"))\n",
"\n",
"row = puzzle\n",
"out = 0\n",
"for _ in range(40):\n",
" out += row.count(\".\")\n",
" row = next_row(row)\n",
"out"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"20006289"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def next_row(row):\n",
" return \"\".join(\".^\"[a!=b] for a, b in zip(\".\" + row[:-1], row[1:] + \".\"))\n",
"\n",
"row = puzzle\n",
"out = 0\n",
"for _ in range(400000):\n",
" out += row.count(\".\")\n",
" row = next_row(row)\n",
"out"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

27
Python/2016/18.py Normal file
View file

@ -0,0 +1,27 @@
from lib import *
input = read_input(2016, 18).strip()
def next_row(row):
return "".join(".^"[a != b] for a, b in zip("." + row[:-1], row[1:] + "."))
row = input
out = 0
for _ in range(40):
out += row.count(".")
row = next_row(row)
print(out)
def next_row(row):
return "".join(".^"[a != b] for a, b in zip("." + row[:-1], row[1:] + "."))
row = input
out = 0
for _ in range(400000):
out += row.count(".")
row = next_row(row)
print(out)

View file

@ -1,115 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 19"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 19\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1808357"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"n = int(puzzle)\n",
"(n-(1<<n.bit_length()-1)<<1)+1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1407007\n"
]
}
],
"source": [
"import math\n",
"\n",
"n = int(puzzle)\n",
"l = int(math.log(n, 3))\n",
"x = 3**l+1\n",
"y = 2*3**l\n",
"z = 3**(l+1)\n",
"if n <= y:\n",
" print(n-x+1)\n",
"else:\n",
" print(n*2-y-x+1)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

17
Python/2016/19.py Normal file
View file

@ -0,0 +1,17 @@
from lib import *
input = read_input(2016, 19)
n = int(input)
print((n - (1 << n.bit_length() - 1) << 1) + 1)
n = int(input)
l = int(math.log(n, 3))
x = 3**l + 1
y = 2 * 3**l
z = 3 ** (l + 1)
if n <= y:
print(n - x + 1)
else:
print(n * 2 - y - x + 1)

View file

@ -1,129 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 20"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 20\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4793564\n"
]
}
],
"source": [
"blocked = []\n",
"for line in puzzle.splitlines():\n",
" a, b = map(int, line.split(\"-\"))\n",
" blocked.append((a, b))\n",
"\n",
"is_blocked = lambda x: any(a<=x<=b for a, b in blocked)\n",
"\n",
"for b in sorted(b for _, b in blocked):\n",
" if not is_blocked(b+1):\n",
" print(b+1)\n",
" break"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"146"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"blocked = []\n",
"for line in puzzle.splitlines():\n",
" a, b = map(int, line.split(\"-\"))\n",
"\n",
" merged = []\n",
" for i, (x, y) in enumerate(blocked):\n",
" if x <= a <= b <= y: break\n",
" if y + 1 < a or b < x - 1: continue\n",
" a, b = min(a, x), max(b, y)\n",
" merged.append(i)\n",
" else:\n",
" blocked.append((a, b))\n",
" for i in reversed(merged):\n",
" blocked.pop(i)\n",
" \n",
"(1<<32)-sum(b-a+1 for a, b in blocked)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

44
Python/2016/20.py Normal file
View file

@ -0,0 +1,44 @@
from lib import *
input = read_input(2016, 20)
blocked = []
for line in input.splitlines():
a, b = map(int, line.split("-"))
blocked.append((a, b))
is_blocked = lambda x: any(a <= x <= b for a, b in blocked)
for b in sorted(b for _, b in blocked):
if not is_blocked(b + 1):
print(b + 1)
break
blocked = []
for line in input.splitlines():
a, b = map(int, line.split("-"))
merged = []
for i, (x, y) in enumerate(blocked):
if x <= a <= b <= y:
break
if y + 1 < a or b < x - 1:
continue
a, b = min(a, x), max(b, y)
merged.append(i)
else:
blocked.append((a, b))
for i in reversed(merged):
blocked.pop(i)
print((1 << 32) - sum(b - a + 1 for a, b in blocked))

View file

@ -1,137 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 21"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 21\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"bgfacdeh\n"
]
}
],
"source": [
"import re\n",
"\n",
"def scramble(inp):\n",
" *out, = inp\n",
" for line in puzzle.splitlines():\n",
" if match := re.match(r\"^swap position (\\d+) with position (\\d+)$\", line):\n",
" x, y = map(int, match.groups())\n",
" out[x], out[y] = out[y], out[x]\n",
" if match := re.match(r\"^swap letter ([a-zA-Z\\d]+) with letter ([a-zA-Z\\d]+)$\", line):\n",
" x, y = match.groups()\n",
" out = [[[c, x][c==y], y][c==x] for c in out]\n",
" if match := re.match(r\"^rotate (left|right) (\\d+) steps?$\", line):\n",
" d, n = match.groups()\n",
" n = int(n)\n",
" if d == \"right\": n *= -1\n",
" n %= len(out)\n",
" out = out[n:] + out[:n]\n",
" if match := re.match(r\"^rotate based on position of letter ([a-zA-Z\\d]+)$\", line):\n",
" x, = match.groups()\n",
" idx = out.index(x)\n",
" n = -(1 + idx + (idx >= 4)) % len(out)\n",
" out = out[n:] + out[:n]\n",
" if match := re.match(r\"^reverse positions (\\d+) through (\\d+)$\", line):\n",
" x, y = sorted(map(int, match.groups()))\n",
" out = out[:x] + out[x:y+1][::-1] + out[y+1:]\n",
" if match := re.match(r\"^move position (\\d+) to position (\\d+)$\", line):\n",
" x, y = map(int, match.groups())\n",
" out.insert(y, out.pop(x))\n",
"\n",
" return \"\".join(out)\n",
"\n",
"print(scramble(\"abcdefgh\"))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"bdgheacf\n"
]
}
],
"source": [
"import itertools\n",
"\n",
"for it in itertools.permutations(\"abcdefgh\"):\n",
" if scramble(inp := \"\".join(it)) == \"fbgdceah\":\n",
" print(inp)\n",
" break"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

61
Python/2016/21.py Normal file
View file

@ -0,0 +1,61 @@
from lib import *
input = read_input(2016, 21)
import re
def scramble(inp):
(*out,) = inp
for line in input.splitlines():
if match := re.match(r"^swap position (\d+) with position (\d+)$", line):
x, y = map(int, match.groups())
out[x], out[y] = out[y], out[x]
if match := re.match(r"^swap letter ([a-zA-Z\d]+) with letter ([a-zA-Z\d]+)$", line):
x, y = match.groups()
out = [[[c, x][c == y], y][c == x] for c in out]
if match := re.match(r"^rotate (left|right) (\d+) steps?$", line):
d, n = match.groups()
n = int(n)
if d == "right":
n *= -1
n %= len(out)
out = out[n:] + out[:n]
if match := re.match(r"^rotate based on position of letter ([a-zA-Z\d]+)$", line):
(x,) = match.groups()
idx = out.index(x)
n = -(1 + idx + (idx >= 4)) % len(out)
out = out[n:] + out[:n]
if match := re.match(r"^reverse positions (\d+) through (\d+)$", line):
x, y = sorted(map(int, match.groups()))
out = out[:x] + out[x : y + 1][::-1] + out[y + 1 :]
if match := re.match(r"^move position (\d+) to position (\d+)$", line):
x, y = map(int, match.groups())
out.insert(y, out.pop(x))
return "".join(out)
print(scramble("abcdefgh"))
for it in itertools.permutations("abcdefgh"):
if scramble(inp := "".join(it)) == "fbgdceah":
print(inp)
break

View file

@ -1,156 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 22"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 22\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"952"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"size = {}\n",
"used = {}\n",
"\n",
"for line in puzzle.splitlines()[2:]:\n",
" node, s, u, *_ = line.split()\n",
" node = tuple(int(x[1:]) for x in node.split(\"-\")[1:])\n",
" s, u = [int(x[:-1]) for x in (s, u)]\n",
" size[node] = s\n",
" used[node] = u\n",
"\n",
"out = 0\n",
"for p1 in size:\n",
" if not used[p1]: continue\n",
" for p2 in size:\n",
" if p1 == p2: continue\n",
" out += used[p1] + used[p2] <= size[p2]\n",
"out"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"181"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"width, height = max((x+1,y+1) for x,y in size)\n",
"target = width - 1\n",
"\n",
"def free(x, y):\n",
" queue = [(x, y, [])]\n",
" visited = set()\n",
" while queue:\n",
" x, y, prev = queue.pop(0)\n",
" \n",
" if not used[(x, y)]:\n",
" for p, q in prev[::-1]:\n",
" used[(x, y)] = used[(p, q)]\n",
" used[(p, q)] = 0\n",
" x, y = p, q\n",
" return len(prev)\n",
" \n",
" if (x, y) in visited: continue\n",
" visited.add((x, y))\n",
" \n",
" for p,q in [(x,y-1),(x,y+1),(x-1,y),(x+1,y)]:\n",
" if p not in range(width) or q not in range(height): continue\n",
" if (p, q) == (target, 0): continue\n",
" if (p, q) in visited: continue\n",
" if used[(x, y)] > size[(p, q)]: continue\n",
" queue.append((p, q, prev + [(x, y)]))\n",
"\n",
"out = 0\n",
"while target:\n",
" out += free(target - 1, 0)\n",
" used[(target-1,0)] = used[(target,0)]\n",
" used[(target,0)] = 0\n",
" target -= 1\n",
" out += 1\n",
"out"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

89
Python/2016/22.py Normal file
View file

@ -0,0 +1,89 @@
from lib import *
input = read_input(2016, 22)
size = {}
used = {}
for line in input.splitlines()[2:]:
node, s, u, *_ = line.split()
node = tuple(int(x[1:]) for x in node.split("-")[1:])
s, u = [int(x[:-1]) for x in (s, u)]
size[node] = s
used[node] = u
out = 0
for p1 in size:
if not used[p1]:
continue
for p2 in size:
if p1 == p2:
continue
out += used[p1] + used[p2] <= size[p2]
print(out)
width, height = max((x + 1, y + 1) for x, y in size)
target = width - 1
def free(x, y):
queue = [(x, y, [])]
visited = set()
while queue:
x, y, prev = queue.pop(0)
if not used[(x, y)]:
for p, q in prev[::-1]:
used[(x, y)] = used[(p, q)]
used[(p, q)] = 0
x, y = p, q
return len(prev)
if (x, y) in visited:
continue
visited.add((x, y))
for p, q in [(x, y - 1), (x, y + 1), (x - 1, y), (x + 1, y)]:
if p not in range(width) or q not in range(height):
continue
if (p, q) == (target, 0):
continue
if (p, q) in visited:
continue
if used[(x, y)] > size[(p, q)]:
continue
queue.append((p, q, prev + [(x, y)]))
out = 0
while target:
out += free(target - 1, 0)
used[(target - 1, 0)] = used[(target, 0)]
used[(target, 0)] = 0
target -= 1
out += 1
print(out)

View file

@ -1,149 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 23"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 23\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"11004"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"program = puzzle.splitlines()\n",
"registers = {k: 0 for k in \"abcd\"}\n",
"\n",
"def simulate():\n",
" pc = 0\n",
" while pc < len(program):\n",
" cmd, x, y, *_ = program[pc].split() + [None]\n",
" read = lambda a: registers[a] if a in registers else int(a)\n",
" if cmd == \"cpy\":\n",
" if y in registers:\n",
" registers[y] = read(x)\n",
" pc += 1\n",
" elif cmd == \"inc\":\n",
" if x in registers:\n",
" registers[x] += 1\n",
" pc += 1\n",
" elif cmd == \"dec\":\n",
" if x in registers:\n",
" registers[x] -= 1\n",
" pc += 1\n",
" elif cmd == \"jnz\":\n",
" if read(x) and y is not None:\n",
" pc += read(y) or 1\n",
" else:\n",
" pc += 1\n",
" elif cmd == \"tgl\":\n",
" if pc + (x := read(x)) in range(len(program)):\n",
" cmd, args = program[pc + x].split(maxsplit=1)\n",
" if cmd == \"inc\": cmd = \"dec\"\n",
" elif cmd in [\"dec\", \"tgl\"]: cmd = \"inc\"\n",
" elif cmd == \"jnz\": cmd = \"cpy\"\n",
" elif cmd in [\"cpy\"]: cmd = \"jnz\"\n",
" program[pc + x] = f\"{cmd} {args}\"\n",
" pc += 1\n",
" return registers[\"a\"]\n",
"\n",
"registers[\"a\"] = 7\n",
"simulate()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"479007564"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import math\n",
"\n",
"program = puzzle.splitlines()\n",
"registers = {k: 0 for k in \"abcd\"}\n",
"registers[\"a\"] = 7\n",
"math.factorial(12) + simulate() - math.factorial(7)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

73
Python/2016/23.py Normal file
View file

@ -0,0 +1,73 @@
from lib import *
input = read_input(2016, 23)
program = input.splitlines()
registers = {k: 0 for k in "abcd"}
def simulate():
pc = 0
while pc < len(program):
cmd, x, y, *_ = program[pc].split() + [None]
read = lambda a: registers[a] if a in registers else int(a)
if cmd == "cpy":
if y in registers:
registers[y] = read(x)
pc += 1
elif cmd == "inc":
if x in registers:
registers[x] += 1
pc += 1
elif cmd == "dec":
if x in registers:
registers[x] -= 1
pc += 1
elif cmd == "jnz":
if read(x) and y is not None:
pc += read(y) or 1
else:
pc += 1
elif cmd == "tgl":
if pc + (x := read(x)) in range(len(program)):
cmd, args = program[pc + x].split(maxsplit=1)
if cmd == "inc":
cmd = "dec"
elif cmd in ["dec", "tgl"]:
cmd = "inc"
elif cmd == "jnz":
cmd = "cpy"
elif cmd in ["cpy"]:
cmd = "jnz"
program[pc + x] = f"{cmd} {args}"
pc += 1
return registers["a"]
registers["a"] = 7
print(simulate())
program = input.splitlines()
registers = {k: 0 for k in "abcd"}
registers["a"] = 7
print(math.factorial(12) + simulate() - math.factorial(7))

View file

@ -1,163 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 24"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 24\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{2: (165, 1), 1: (5, 3), 3: (177, 7), 0: (3, 17), 7: (173, 23), 6: (27, 31), 5: (167, 35), 4: (47, 37)}\n"
]
},
{
"data": {
"text/plain": [
"498"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import itertools\n",
"\n",
"grid = puzzle.splitlines()\n",
"nodes = {}\n",
"rnodes = {}\n",
"for i, line in enumerate(grid):\n",
" for j, c in enumerate(line):\n",
" if c.isnumeric():\n",
" nodes[int(c)] = j, i\n",
" rnodes[(j, i)] = int(c)\n",
"print(nodes)\n",
"\n",
"def asp(x, y):\n",
" queue = [(0, x, y)]\n",
" out = {}\n",
" visited = set()\n",
" while queue: \n",
" d, x, y = queue.pop(0)\n",
" \n",
" if (x, y) in visited: continue\n",
" visited.add((x, y))\n",
" \n",
" if (x, y) in rnodes:\n",
" out[rnodes[(x,y)]] = d\n",
" \n",
" for p, q in [(x,y-1),(x,y+1),(x-1,y),(x+1,y)]:\n",
" if p not in range(len(grid[0])) or q not in range(len(grid)) or grid[q][p] == \"#\":\n",
" continue\n",
" queue.append((d + 1, p, q))\n",
" \n",
" return out\n",
"\n",
"sp = {k: asp(*v) for k, v in nodes.items()}\n",
"best = 1e1337\n",
"for order in itertools.permutations(set(sp) - {0}):\n",
" pos = 0\n",
" cost = 0\n",
" for x in order:\n",
" cost += sp[pos][x]\n",
" pos = x\n",
" best = min(best, cost)\n",
"best"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"804"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"best = 1e1337\n",
"for order in itertools.permutations(set(sp) - {0}):\n",
" pos = 0\n",
" cost = 0\n",
" for x in order:\n",
" cost += sp[pos][x]\n",
" pos = x\n",
" best = min(best, cost + sp[pos][0])\n",
"best"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

80
Python/2016/24.py Normal file
View file

@ -0,0 +1,80 @@
from lib import *
input = read_input(2016, 24)
grid = input.splitlines()
nodes = {}
rnodes = {}
for i, line in enumerate(grid):
for j, c in enumerate(line):
if c.isnumeric():
nodes[int(c)] = j, i
rnodes[(j, i)] = int(c)
def asp(x, y):
queue = [(0, x, y)]
out = {}
visited = set()
while queue:
d, x, y = queue.pop(0)
if (x, y) in visited:
continue
visited.add((x, y))
if (x, y) in rnodes:
out[rnodes[(x, y)]] = d
for p, q in [(x, y - 1), (x, y + 1), (x - 1, y), (x + 1, y)]:
if p not in range(len(grid[0])) or q not in range(len(grid)) or grid[q][p] == "#":
continue
queue.append((d + 1, p, q))
return out
sp = {k: asp(*v) for k, v in nodes.items()}
best = 1e1337
for order in itertools.permutations(set(sp) - {0}):
pos = 0
cost = 0
for x in order:
cost += sp[pos][x]
pos = x
best = min(best, cost)
print(best)
best = 1e1337
for order in itertools.permutations(set(sp) - {0}):
pos = 0
cost = 0
for x in order:
cost += sp[pos][x]
pos = x
best = min(best, cost + sp[pos][0])
print(best)

View file

@ -1,118 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"# Day 25"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import sys; sys.path.insert(0, \"..\")\n",
"\n",
"import aoc\n",
"\n",
"year, day = 2016, 25\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"182"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"program = puzzle.splitlines()\n",
"\n",
"def simulate(a):\n",
" registers = {k: 0 for k in \"abcd\"}\n",
" registers[\"a\"] = a\n",
" pc = 0\n",
" while pc < len(program):\n",
" cmd, x, y, *_ = program[pc].split() + [None]\n",
" read = lambda a: registers[a] if a in registers else int(a)\n",
" if cmd == \"cpy\":\n",
" if y in registers:\n",
" registers[y] = read(x)\n",
" pc += 1\n",
" elif cmd == \"inc\":\n",
" if x in registers:\n",
" registers[x] += 1\n",
" pc += 1\n",
" elif cmd == \"dec\":\n",
" if x in registers:\n",
" registers[x] -= 1\n",
" pc += 1\n",
" elif cmd == \"jnz\":\n",
" if read(x) and y is not None:\n",
" pc += read(y) or 1\n",
" else:\n",
" pc += 1\n",
" elif cmd == \"out\":\n",
" yield read(x)\n",
" pc += 1\n",
"\n",
"def test(a):\n",
" for i, x in enumerate(simulate(a)):\n",
" if i % 2 != x: return False\n",
" if i > 100: return True\n",
" return False\n",
"\n",
"a = 0\n",
"while not test(a): a += 1\n",
"a"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

52
Python/2016/25.py Normal file
View file

@ -0,0 +1,52 @@
from lib import *
input = read_input(2016, 25)
program = input.splitlines()
def simulate(a):
registers = {k: 0 for k in "abcd"}
registers["a"] = a
pc = 0
while pc < len(program):
cmd, x, y, *_ = program[pc].split() + [None]
read = lambda a: registers[a] if a in registers else int(a)
if cmd == "cpy":
if y in registers:
registers[y] = read(x)
pc += 1
elif cmd == "inc":
if x in registers:
registers[x] += 1
pc += 1
elif cmd == "dec":
if x in registers:
registers[x] -= 1
pc += 1
elif cmd == "jnz":
if read(x) and y is not None:
pc += read(y) or 1
else:
pc += 1
elif cmd == "out":
yield read(x)
pc += 1
def test(a):
for i, x in enumerate(simulate(a)):
if i % 2 != x:
return False
if i > 100:
return True
return False
a = 0
while not test(a):
a += 1
print(a)