Move Python solutions

This commit is contained in:
Felix Bargfeldt 2023-10-19 22:06:58 +02:00
parent 6fae773051
commit 2f1872bbd9
Signed by: Defelo
GPG key ID: 2A05272471204DD3
255 changed files with 0 additions and 4323 deletions

109
Python/2015/01.ipynb Normal file
View file

@ -0,0 +1,109 @@
{
"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 = 2015, 1\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": [
"138"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x = 0\n",
"cum = [(x := x + [-1,1][c==\"(\"]) for c in puzzle]\n",
"cum[-1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1771"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"cum.index(-1) + 1"
]
}
],
"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
}

114
Python/2015/02.ipynb Normal file
View file

@ -0,0 +1,114 @@
{
"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 = 2015, 2\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": [
"1586300"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"boxes = [sorted(map(int, line.split(\"x\"))) for line in puzzle.splitlines()]\n",
"total = 0\n",
"for a, b, c in boxes:\n",
" total += 2*(a*b+a*c+b*c) + a*b\n",
"total"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3737498"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"total = 0\n",
"for a, b, c in boxes:\n",
" total += 2*(a+b) + a*b*c\n",
"total"
]
}
],
"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
}

117
Python/2015/03.ipynb Normal file
View file

@ -0,0 +1,117 @@
{
"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 = 2015, 3\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": [
"2572"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def get_houses(instructions):\n",
" houses = [(x:=0, y:=0)]\n",
" for c in instructions:\n",
" x += c==\">\"\n",
" x -= c==\"<\"\n",
" y += c==\"v\"\n",
" y -= c==\"^\"\n",
" houses.append((x, y))\n",
" return houses\n",
"\n",
"len(set(get_houses(puzzle)))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2631"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"len(set(get_houses(puzzle[::2])) | set(get_houses(puzzle[1::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
}

118
Python/2015/04.ipynb Normal file
View file

@ -0,0 +1,118 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"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 = 2015, 4\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": [
"117946"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import hashlib\n",
"\n",
"def check(inp, cnt):\n",
" return hashlib.md5(inp.encode()).hexdigest().startswith(\"0\" * cnt)\n",
"\n",
"def mine(cnt):\n",
" i = 1\n",
" while not check(f\"{puzzle}{i}\", cnt):\n",
" i += 1\n",
" return i\n",
"\n",
"mine(5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3938038"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"mine(6)"
]
}
],
"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
}

115
Python/2015/05.ipynb Normal file
View file

@ -0,0 +1,115 @@
{
"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 = 2015, 5\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": [
"238"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import re\n",
"\n",
"def is_nice(x):\n",
" return bool(re.match(r\"^(?=(.*[aeiou]){3,})(?=.*(?P<x>.)(?P=x)).*$\", x)) and not any(e in x for e in [\"ab\", \"cd\", \"pq\", \"xy\"])\n",
"\n",
"sum(map(is_nice, puzzle.splitlines()))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"69"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def is_nice(x):\n",
" return bool(re.match(r\"^(?=.*(?P<a>..).*(?P=a))(?=.*(?P<b>.).(?P=b)).*$\", x))\n",
"\n",
"sum(map(is_nice, 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
}

126
Python/2015/06.ipynb Normal file
View file

@ -0,0 +1,126 @@
{
"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 = 2015, 6\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": [
"377891"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import re\n",
"\n",
"def parse_instructions(instructions):\n",
" out = []\n",
" for line in instructions:\n",
" inst, *coords = re.match(r\"^([a-z ]+) (\\d+),(\\d+) through (\\d+),(\\d+)$\", line).groups()\n",
" out.append(([\"turn off\", \"turn on\", \"toggle\"].index(inst), *map(int, coords)))\n",
" return out\n",
"\n",
"lights = [[0 for _ in range(1000)] for _ in range(1000)]\n",
"for inst, x1, y1, x2, y2 in parse_instructions(puzzle.splitlines()):\n",
" for y in range(y1, y2+1):\n",
" for x in range(x1, x2+1):\n",
" lights[y][x] = 1 - lights[y][x] if inst == 2 else inst\n",
"sum(map(sum, lights))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"14110788"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"lights = [[0 for _ in range(1000)] for _ in range(1000)]\n",
"for inst, x1, y1, x2, y2 in parse_instructions(puzzle.splitlines()):\n",
" for y in range(y1, y2+1):\n",
" for x in range(x1, x2+1):\n",
" lights[y][x] = max(0, lights[y][x] + (inst or -1))\n",
"sum(map(sum, lights))"
]
}
],
"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
}

139
Python/2015/07.ipynb Normal file
View file

@ -0,0 +1,139 @@
{
"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 = 2015, 7\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"956"
]
},
"execution_count": 37,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"MOD = 1<<16\n",
"\n",
"funcs = {dest: args for *args, _, dest in map(str.split, puzzle.splitlines())}\n",
"\n",
"dp = {}\n",
"\n",
"def solve(key):\n",
" if key not in dp:\n",
" if key.isnumeric():\n",
" val = int(key)\n",
" else:\n",
" args = funcs[key]\n",
" if len(args) == 1:\n",
" val = solve(args[0])\n",
" elif len(args) == 2:\n",
" if args[0] == \"NOT\":\n",
" val = ~solve(args[1]) % MOD\n",
" elif len(args) == 3:\n",
" if args[1] == \"OR\":\n",
" val = solve(args[0]) | solve(args[2])\n",
" elif args[1] == \"AND\":\n",
" val = solve(args[0]) & solve(args[2])\n",
" elif args[1] == \"LSHIFT\":\n",
" val = solve(args[0]) << solve(args[2])\n",
" elif args[1] == \"RSHIFT\":\n",
" val = solve(args[0]) >> solve(args[2])\n",
" dp[key] = val % MOD\n",
" \n",
" return dp[key]\n",
"\n",
"solve(\"a\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"40149"
]
},
"execution_count": 38,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dp.clear()\n",
"dp = {\"b\": solve(\"a\")}\n",
"solve(\"a\")"
]
}
],
"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
}

107
Python/2015/08.ipynb Normal file
View file

@ -0,0 +1,107 @@
{
"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 = 2015, 8\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1342"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sum(len(line) - len(eval(line)) for line in puzzle.splitlines())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2074"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sum(len(repr(line))+line.count('\"') - len(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
}

114
Python/2015/09.ipynb Normal file
View file

@ -0,0 +1,114 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"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 = 2015, 9\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": [
"207"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import itertools\n",
"\n",
"graph = {}\n",
"for src, _, dst, _, dist in map(str.split, puzzle.splitlines()):\n",
" graph.setdefault(src, {})[dst] = int(dist)\n",
" graph.setdefault(dst, {})[src] = int(dist)\n",
"\n",
"min(sum(graph[a][b] for a, b in zip(locs, locs[1:])) for locs in itertools.permutations(graph))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"804"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"max(sum(graph[a][b] for a, b in zip(locs, locs[1:])) for locs in itertools.permutations(graph))"
]
}
],
"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
}

125
Python/2015/10.ipynb Normal file
View file

@ -0,0 +1,125 @@
{
"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 = 2015, 10\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": [
"329356"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def las(inp):\n",
" out = \"\"\n",
" i = 0\n",
" while i < len(inp):\n",
" c = inp[i]\n",
" j = 1\n",
" while i+j < len(inp) and inp[i+j] == c:\n",
" j += 1\n",
" out += f\"{j}{c}\"\n",
" i += j\n",
" return out\n",
"\n",
"x = puzzle\n",
"for _ in range(40):\n",
" x = las(x)\n",
"len(x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"4666278"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x = puzzle\n",
"for _ in range(50):\n",
" x = las(x)\n",
"len(x)"
]
}
],
"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
}

127
Python/2015/11.ipynb Normal file
View file

@ -0,0 +1,127 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"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 = 2015, 11\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'cqjxxyzz'"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def inc(x):\n",
" x = [ord(c)-0x61 for c in x]\n",
" for i in range(len(x))[::-1]:\n",
" x[i] += 1\n",
" while chr(0x61+x[i]) in \"iol\":\n",
" x[i] += 1\n",
" if x[i] < 26:\n",
" break\n",
" x[i] = 0\n",
" return \"\".join(chr(c+0x61) for c in x)\n",
"\n",
"def check(x):\n",
" return all(c not in x for c in \"iol\") and any((chr(i)+chr(i+1)+chr(i+2)) in x for i in range(0x61,0x61+24)) and sum(chr(0x61+i)*2 in x for i in range(26))>=2\n",
"\n",
"def nxt(x):\n",
" x = inc(x)\n",
" while not check(x):\n",
" x = inc(x)\n",
" return x\n",
"\n",
"nxt(puzzle)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'cqkaabcc'"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"nxt(nxt(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
}

131
Python/2015/12.ipynb Normal file
View file

@ -0,0 +1,131 @@
{
"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 = 2015, 12\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"111754"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import json\n",
"\n",
"data = json.loads(puzzle)\n",
"\n",
"def count(obj):\n",
" if isinstance(obj, dict):\n",
" return sum(map(count, obj.values()))\n",
" elif isinstance(obj, list):\n",
" return sum(map(count, obj))\n",
" elif isinstance(obj, int):\n",
" return obj\n",
" return 0\n",
"\n",
"count(data)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"65402"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def count(obj):\n",
" if isinstance(obj, dict):\n",
" if \"red\" in obj.values():\n",
" return 0\n",
" return sum(map(count, obj.values()))\n",
" elif isinstance(obj, list):\n",
" return sum(map(count, obj))\n",
" elif isinstance(obj, int):\n",
" return obj\n",
" return 0\n",
"\n",
"count(data)"
]
}
],
"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
}

121
Python/2015/13.ipynb Normal file
View file

@ -0,0 +1,121 @@
{
"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 = 2015, 13\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"733"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import itertools\n",
"\n",
"hp = {}\n",
"\n",
"for a, _, m, c, *_, b in map(str.split, puzzle.splitlines()):\n",
" b = b[:-1]\n",
" c = int(c)\n",
" if m == \"lose\":\n",
" c *= -1\n",
" hp.setdefault(b, {})[a] = hp[a][b] = hp.setdefault(a, {}).get(b, 0) + c\n",
"\n",
"def calc(table):\n",
" return sum(hp.get(table[i],{}).get(table[(i+1)%len(table)],0) for i in range(len(table)))\n",
"\n",
"max(map(calc, itertools.permutations(hp)))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"725"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"max(map(calc, itertools.permutations([*hp,\"_\"])))"
]
}
],
"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
}

134
Python/2015/14.ipynb Normal file
View file

@ -0,0 +1,134 @@
{
"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 = 2015, 14\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2640"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"T = 2503\n",
"out = 0\n",
"\n",
"for line in map(str.split, puzzle.splitlines()):\n",
" v, t, r = map(int, [line[3], line[6], line[-2]])\n",
" x = T // (t + r) * t * v\n",
" x += min(t, T % (t + r)) * v\n",
" out = max(out, x)\n",
"out"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1102"
]
},
"execution_count": 37,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"T = 2503\n",
"\n",
"reindeers = [tuple(map(int, [line[3], line[6], line[-2]])) for line in map(str.split, puzzle.splitlines())]\n",
"states = [0]*len(reindeers)\n",
"meters = [0]*len(reindeers)\n",
"bonus = [0]*len(reindeers)\n",
"\n",
"for _ in range(T):\n",
" for i, (v, t, r) in enumerate(reindeers):\n",
" if states[i] >= 0:\n",
" meters[i] += v\n",
" states[i] += 1\n",
" if states[i] >= t:\n",
" states[i] = -r\n",
" mx = max(meters)\n",
" for i, m in enumerate(meters):\n",
" if m == mx:\n",
" bonus[i] += 1\n",
"\n",
"max(bonus)"
]
}
],
"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
}

133
Python/2015/15.ipynb Normal file
View file

@ -0,0 +1,133 @@
{
"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 = 2015, 15\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"13882464"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"TOTAL = 100\n",
"\n",
"ingredients = [[int(x.strip(\",\")) for x in i[2:-1:2]] for i in map(str.split, puzzle.splitlines())]\n",
"\n",
"def solve(i, x, prev):\n",
" if i == len(ingredients)-1:\n",
" out = 1\n",
" for p,e in zip(prev,ingredients[-1]):\n",
" out *= max(0, p+x*e)\n",
" return out\n",
" \n",
" return max(solve(i + 1, x - j, [a+j*b for a, b in zip(prev, ingredients[i])]) for j in range(x + 1))\n",
"\n",
"solve(0, TOTAL, [0]*4)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"11171160"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"ingredients = [[int(x.strip(\",\")) for x in i[2::2]] for i in map(str.split, puzzle.splitlines())]\n",
"\n",
"def solve(i, x, prev):\n",
" if i == len(ingredients)-1:\n",
" if prev[-1]+x*ingredients[-1][-1] != 500:\n",
" return 0\n",
" out = 1\n",
" for p,e in zip(prev[:-1],ingredients[-1][:-1]):\n",
" out *= max(0, p+x*e)\n",
" return out\n",
" \n",
" return max(solve(i + 1, x - j, [a+j*b for a, b in zip(prev, ingredients[i])]) for j in range(x + 1))\n",
"\n",
"solve(0, TOTAL, [0]*5)"
]
}
],
"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
}

132
Python/2015/16.ipynb Normal file
View file

@ -0,0 +1,132 @@
{
"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 = 2015, 16\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"373"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"aunts = [{k:int(v) for k, v in map(str.split, \"\".join(line.split()[2:]).replace(\":\",\" \").split(\",\"))} for line in puzzle.splitlines()]\n",
"\n",
"sue = {\n",
" \"children\": 3,\n",
" \"cats\": 7,\n",
" \"samoyeds\": 2,\n",
" \"pomeranians\": 3,\n",
" \"akitas\": 0,\n",
" \"vizslas\": 0,\n",
" \"goldfish\": 5,\n",
" \"trees\": 3,\n",
" \"cars\": 2,\n",
" \"perfumes\": 1,\n",
"}\n",
"\n",
"for i, x in enumerate(aunts):\n",
" if all(k not in x or x[k]==v for k, v in sue.items()):\n",
" break\n",
"i+1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"260"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"for i, x in enumerate(aunts):\n",
" if not all(k not in x or x[k]>sue[k] for k in [\"cats\",\"trees\"]):\n",
" continue\n",
" if not all(k not in x or x[k]<sue[k] for k in [\"pomeranians\",\"goldfish\"]):\n",
" continue\n",
" if all(k not in x or x[k]==v for k, v in sue.items() if k not in [\"cats\",\"trees\",\"pomeranians\",\"goldfish\"]):\n",
" break\n",
"i+1"
]
}
],
"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
}

142
Python/2015/17.ipynb Normal file
View file

@ -0,0 +1,142 @@
{
"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 = 2015, 17\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1638"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"containers = list(map(int, puzzle.splitlines()))\n",
"dp = {}\n",
"\n",
"def solve(i, x):\n",
" if i == len(containers):\n",
" return int(x == 0)\n",
" \n",
" if (i,x) not in dp:\n",
" out = solve(i + 1, x)\n",
" if containers[i] <= x:\n",
" out += solve(i + 1, x - containers[i])\n",
" dp[(i, x)] = out\n",
" return dp[(i, x)]\n",
"\n",
"solve(0, 150)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"17"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"containers = list(map(int, puzzle.splitlines()))\n",
"dp = {}\n",
"\n",
"def solve(i, x):\n",
" if i == len(containers):\n",
" return None if x else (0, 1)\n",
" \n",
" if (i,x) not in dp:\n",
" out = solve(i + 1, x)\n",
" if containers[i] <= x:\n",
" y = solve(i + 1, x - containers[i])\n",
" if y is not None:\n",
" l, c = y\n",
" l += 1\n",
" if out is None or l < out[0]:\n",
" out = l, c\n",
" elif out is not None and out[0] == l:\n",
" out = l, out[1] + c\n",
" dp[(i, x)] = out\n",
" return dp[(i, x)]\n",
"\n",
"solve(0, 150)[1]"
]
}
],
"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
}

130
Python/2015/18.ipynb Normal file
View file

@ -0,0 +1,130 @@
{
"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 = 2015, 18\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"814"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"gol = puzzle.splitlines()\n",
"\n",
"for _ in range(100):\n",
" gol = [\n",
" [\n",
" \".#\"[(cnt:=sum(gol[p][q]==\"#\" for r in range(3) for s in range(3) if (r,s)!=(1,1) and 0<=(p:=i-1+r)<len(gol) and 0<=(q:=j-1+s)<len(row))) in (2,3) and x==\"#\" or x==\".\" and cnt==3]\n",
" for j, x in enumerate(row)\n",
" ]\n",
" for i, row in enumerate(gol)\n",
" ]\n",
"sum(x==\"#\" for row in gol for x in row)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"924"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"gol = list(map(list, puzzle.splitlines()))\n",
"gol[0][0] = gol[0][-1] = gol[-1][0] = gol[-1][-1] = \"#\"\n",
"\n",
"for _ in range(100):\n",
" gol = [\n",
" [\n",
" \".#\"[(cnt:=sum(gol[p][q]==\"#\" for r in range(3) for s in range(3) if (r,s)!=(1,1) and 0<=(p:=i-1+r)<len(gol) and 0<=(q:=j-1+s)<len(row))) in (2,3) and x==\"#\" or x==\".\" and cnt==3]\n",
" for j, x in enumerate(row)\n",
" ]\n",
" for i, row in enumerate(gol)\n",
" ]\n",
" gol[0][0] = gol[0][-1] = gol[-1][0] = gol[-1][-1] = \"#\"\n",
" \n",
"sum(x==\"#\" for row in gol for x in row)"
]
}
],
"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
}

139
Python/2015/19.ipynb Normal file
View file

@ -0,0 +1,139 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 18,
"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 = 2015, 19\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"518"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"*replacements, _, mol = puzzle.splitlines()\n",
"rep = {}\n",
"for k, _, v in map(str.split, replacements):\n",
" rep.setdefault(k, []).append(v)\n",
"\n",
"out = set()\n",
"for k, v in rep.items():\n",
" for i in range(len(mol)):\n",
" if k == mol[i:i+len(k)]:\n",
" for e in v:\n",
" out.add(mol[:i] + e + mol[i+len(k):])\n",
"len(out)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 78,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"200"
]
},
"execution_count": 78,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"*replacements, _, mol = puzzle.splitlines()\n",
"rep = {}\n",
"for v, _, k in map(str.split, replacements):\n",
" rep[k] = v\n",
"\n",
"def replace(inp):\n",
" out = set()\n",
" for k, v in rep.items():\n",
" for i in range(len(inp)):\n",
" if k == inp[i:i+len(k)]:\n",
" out.add(inp[:i] + v + inp[i+len(k):])\n",
" return out\n",
"\n",
"def solve(inp):\n",
" if inp == \"e\":\n",
" return 0\n",
" \n",
" for x in replace(inp):\n",
" if (y := solve(x)) is not None:\n",
" return y + 1\n",
"\n",
"solve(mol)"
]
}
],
"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
}

131
Python/2015/20.ipynb Normal file
View file

@ -0,0 +1,131 @@
{
"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 = 2015, 20\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"665280"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"target = int(puzzle) // 10\n",
"\n",
"houses = [0] * target\n",
"for i in range(1, target + 1):\n",
" k = i-1\n",
" while k < target:\n",
" houses[k] += i\n",
" k += i\n",
"for i, x in enumerate(houses):\n",
" if x >= target:\n",
" break\n",
"i+1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"705600"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"target = int(puzzle) // 11\n",
"\n",
"houses = [0] * target\n",
"for i in range(1, target + 1):\n",
" k = i-1\n",
" c = 0\n",
" while k < target and c < 50:\n",
" c += 1\n",
" houses[k] += i\n",
" k += i\n",
"for i, x in enumerate(houses):\n",
" if x >= target:\n",
" break\n",
"i+1"
]
}
],
"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
}

169
Python/2015/21.ipynb Normal file
View file

@ -0,0 +1,169 @@
{
"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 = 2015, 21\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"111"
]
},
"execution_count": 43,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(*_, boss_hp), (*_, boss_damage), (*_, boss_armor) = map(str.split, puzzle.splitlines())\n",
"boss_hp, boss_damage, boss_armor = map(int, [boss_hp, boss_damage, boss_armor])\n",
"\n",
"player_hp = 100\n",
"\n",
"NEUTRAL = (0, 0, 0)\n",
"shop_weapons = [\n",
" (8, 4, 0),\n",
" (10, 5, 0),\n",
" (25, 6, 0),\n",
" (40, 7, 0),\n",
" (74, 8, 0),\n",
"]\n",
"shop_armor = [\n",
" NEUTRAL,\n",
" (13, 0, 1),\n",
" (31, 0, 2),\n",
" (53, 0, 3),\n",
" (75, 0, 4),\n",
" (102, 0, 5),\n",
"]\n",
"shop_rings = [\n",
" NEUTRAL,\n",
" NEUTRAL,\n",
" (25, 1, 0),\n",
" (50, 2, 0),\n",
" (100, 3, 0),\n",
" (20, 0, 1),\n",
" (40, 0, 2),\n",
" (80, 0, 3),\n",
"]\n",
"\n",
"def fight(player_damage, player_armor):\n",
" player = player_hp\n",
" boss = boss_hp\n",
" while True:\n",
" boss -= max(1, player_damage - boss_armor)\n",
" if boss <= 0:\n",
" return True\n",
" player -= max(1, boss_damage - player_armor)\n",
" if player <= 0:\n",
" return False\n",
"\n",
"def combine(*args):\n",
" return tuple(map(sum, zip(*args)))\n",
" \n",
"best = 1e1337\n",
"for weapon in shop_weapons:\n",
" for armor in shop_armor:\n",
" for i, ring1 in enumerate(shop_rings):\n",
" for ring2 in shop_rings[i+1:]:\n",
" cost, d, a = combine(weapon, armor, ring1, ring2)\n",
" if fight(d, a):\n",
" best = min(best, cost)\n",
"best"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"188"
]
},
"execution_count": 44,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"best = 0\n",
"for weapon in shop_weapons:\n",
" for armor in shop_armor:\n",
" for i, ring1 in enumerate(shop_rings):\n",
" for ring2 in shop_rings[i+1:]:\n",
" cost, d, a = combine(weapon, armor, ring1, ring2)\n",
" if not fight(d, a):\n",
" best = max(best, cost)\n",
"best"
]
}
],
"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
}

213
Python/2015/22.ipynb Normal file
View file

@ -0,0 +1,213 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"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 = 2015, 22\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": [
"1824"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(*_, boss_hp), (*_, boss_damage) = map(str.split, puzzle.splitlines())\n",
"boss_hp, boss_damage = map(int, [boss_hp, boss_damage])\n",
"\n",
"player_hp = 50\n",
"player_mana = 500\n",
"\n",
"\n",
"def tick(*timers):\n",
" return [max(0, t - 1) for t in timers]\n",
"\n",
"def fight_boss(player, boss, mana, shield_timer, poison_timer, recharge_timer):\n",
" armor = 7 if shield_timer else 0\n",
" if poison_timer:\n",
" boss -= 3\n",
" if recharge_timer:\n",
" mana += 101\n",
" shield_timer, poison_timer, recharge_timer = tick(shield_timer, poison_timer, recharge_timer)\n",
" \n",
" if boss <= 0:\n",
" return 0\n",
"\n",
" return fight_player(player - max(1, boss_damage - armor), boss, mana, shield_timer, poison_timer, recharge_timer)\n",
"\n",
"def fight_player(player, boss, mana, shield_timer, poison_timer, recharge_timer):\n",
" if player <= 0:\n",
" return None\n",
" \n",
" if poison_timer:\n",
" boss -= 3\n",
" if recharge_timer:\n",
" mana += 101\n",
" shield_timer, poison_timer, recharge_timer = tick(shield_timer, poison_timer, recharge_timer)\n",
"\n",
" if boss <= 0:\n",
" return 0\n",
"\n",
" out = []\n",
" \n",
" # Magic Missile costs 53 mana. It instantly does 4 damage.\n",
" if mana >= 53 and (x := fight_boss(player, boss - 4, mana - 53, shield_timer, poison_timer, recharge_timer)) is not None:\n",
" out.append(x + 53)\n",
" \n",
" # Drain costs 73 mana. It instantly does 2 damage and heals you for 2 hit points.\n",
" if mana >= 73 and (x := fight_boss(player + 2, boss - 2, mana - 73, shield_timer, poison_timer, recharge_timer)) is not None:\n",
" out.append(x + 73)\n",
"\n",
" # Shield costs 113 mana. It starts an effect that lasts for 6 turns. \n",
" # While it is active, your armor is increased by 7.\n",
" if mana >= 113 and not shield_timer and (x := fight_boss(player, boss, mana - 113, 6, poison_timer, recharge_timer)) is not None:\n",
" out.append(x + 113)\n",
" \n",
" # Poison costs 173 mana. It starts an effect that lasts for 6 turns. \n",
" # At the start of each turn while it is active, it deals the boss 3 damage.\n",
" if mana >= 173 and not poison_timer and (x := fight_boss(player, boss, mana - 173, shield_timer, 6, recharge_timer)) is not None:\n",
" out.append(x + 173)\n",
" \n",
" # Recharge costs 229 mana. It starts an effect that lasts for 5 turns. \n",
" # At the start of each turn while it is active, it gives you 101 new mana.\n",
" if mana >= 229 and not recharge_timer and (x := fight_boss(player, boss, mana - 229, shield_timer, poison_timer, 5)) is not None:\n",
" out.append(x + 229)\n",
" \n",
" return min(out, default=None)\n",
"\n",
"\n",
"fight_player(player_hp, boss_hp, player_mana, 0, 0, 0)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1937"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def fight_player(player, boss, mana, shield_timer, poison_timer, recharge_timer):\n",
" player -= 1\n",
" if player <= 0:\n",
" return None\n",
" \n",
" if poison_timer:\n",
" boss -= 3\n",
" if recharge_timer:\n",
" mana += 101\n",
" shield_timer, poison_timer, recharge_timer = tick(shield_timer, poison_timer, recharge_timer)\n",
"\n",
" if boss <= 0:\n",
" return 0\n",
"\n",
" out = []\n",
" \n",
" # Magic Missile costs 53 mana. It instantly does 4 damage.\n",
" if mana >= 53 and (x := fight_boss(player, boss - 4, mana - 53, shield_timer, poison_timer, recharge_timer)) is not None:\n",
" out.append(x + 53)\n",
" \n",
" # Drain costs 73 mana. It instantly does 2 damage and heals you for 2 hit points.\n",
" if mana >= 73 and (x := fight_boss(player + 2, boss - 2, mana - 73, shield_timer, poison_timer, recharge_timer)) is not None:\n",
" out.append(x + 73)\n",
"\n",
" # Shield costs 113 mana. It starts an effect that lasts for 6 turns. \n",
" # While it is active, your armor is increased by 7.\n",
" if mana >= 113 and not shield_timer and (x := fight_boss(player, boss, mana - 113, 6, poison_timer, recharge_timer)) is not None:\n",
" out.append(x + 113)\n",
" \n",
" # Poison costs 173 mana. It starts an effect that lasts for 6 turns. \n",
" # At the start of each turn while it is active, it deals the boss 3 damage.\n",
" if mana >= 173 and not poison_timer and (x := fight_boss(player, boss, mana - 173, shield_timer, 6, recharge_timer)) is not None:\n",
" out.append(x + 173)\n",
" \n",
" # Recharge costs 229 mana. It starts an effect that lasts for 5 turns. \n",
" # At the start of each turn while it is active, it gives you 101 new mana.\n",
" if mana >= 229 and not recharge_timer and (x := fight_boss(player, boss, mana - 229, shield_timer, poison_timer, 5)) is not None:\n",
" out.append(x + 229)\n",
" \n",
" return min(out, default=None)\n",
"\n",
"\n",
"fight_player(player_hp, boss_hp, player_mana, 0, 0, 0)"
]
}
],
"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
}

154
Python/2015/23.ipynb Normal file
View file

@ -0,0 +1,154 @@
{
"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 = 2015, 23\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"170"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"program = puzzle.splitlines()\n",
"pc = 0\n",
"registers = {\"a\": 0, \"b\": 0}\n",
"while pc < len(program):\n",
" cmd, args = program[pc].split(maxsplit=1)\n",
" args = args.split(\", \")\n",
" if cmd == \"hlf\":\n",
" registers[args[0]] //= 2\n",
" pc += 1\n",
" elif cmd == \"tpl\":\n",
" registers[args[0]] *= 3\n",
" pc += 1\n",
" elif cmd == \"inc\":\n",
" registers[args[0]] += 1\n",
" pc += 1\n",
" elif cmd == \"jmp\":\n",
" pc += int(args[0])\n",
" elif cmd == \"jie\":\n",
" pc += int(args[1]) if registers[args[0]] % 2 == 0 else 1\n",
" elif cmd == \"jio\":\n",
" pc += int(args[1]) if registers[args[0]] == 1 else 1\n",
" else:\n",
" break\n",
"\n",
"registers[\"b\"]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"247"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pc = 0\n",
"registers = {\"a\": 1, \"b\": 0}\n",
"while pc < len(program):\n",
" cmd, args = program[pc].split(maxsplit=1)\n",
" args = args.split(\", \")\n",
" if cmd == \"hlf\":\n",
" registers[args[0]] //= 2\n",
" pc += 1\n",
" elif cmd == \"tpl\":\n",
" registers[args[0]] *= 3\n",
" pc += 1\n",
" elif cmd == \"inc\":\n",
" registers[args[0]] += 1\n",
" pc += 1\n",
" elif cmd == \"jmp\":\n",
" pc += int(args[0])\n",
" elif cmd == \"jie\":\n",
" pc += int(args[1]) if registers[args[0]] % 2 == 0 else 1\n",
" elif cmd == \"jio\":\n",
" pc += int(args[1]) if registers[args[0]] == 1 else 1\n",
" else:\n",
" break\n",
"\n",
"registers[\"b\"]"
]
}
],
"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
}

159
Python/2015/24.ipynb Normal file
View file

@ -0,0 +1,159 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"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 = 2015, 24\n",
"\n",
"puzzle = aoc.setup(year, day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"11266889531"
]
},
"execution_count": 39,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"packages = list(map(int, puzzle.splitlines()))\n",
"gs = sum(packages) // 3\n",
"\n",
"dp = {}\n",
"def test(i, x, pkg):\n",
" if x == 0:\n",
" return [[]]\n",
" if i == len(pkg):\n",
" return []\n",
" \n",
" if (i, x) not in dp:\n",
" out = [[0] + y for y in test(i + 1, x, pkg)]\n",
" if packages[i] <= x:\n",
" out += [[1] + y for y in test(i + 1, x - pkg[i], pkg)]\n",
" dp[(i, x)] = out\n",
" return dp[(i, x)]\n",
"\n",
"arr = []\n",
"for x in test(0, gs, packages):\n",
" f = [z for y, z in zip(x, packages) if y]\n",
" if not test(0, gs, f):\n",
" continue\n",
" p = 1\n",
" for y in f:\n",
" p *= y\n",
" arr.append((len(f), p))\n",
"min(arr)[1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"77387711"
]
},
"execution_count": 40,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"packages = list(map(int, puzzle.splitlines()))\n",
"gs = sum(packages) // 4\n",
"\n",
"dp = {}\n",
"def test(i, x, pkg):\n",
" if x == 0:\n",
" return [[]]\n",
" if i == len(pkg):\n",
" return []\n",
" \n",
" if (i, x) not in dp:\n",
" out = [[0] + y for y in test(i + 1, x, pkg)]\n",
" if packages[i] <= x:\n",
" out += [[1] + y for y in test(i + 1, x - pkg[i], pkg)]\n",
" dp[(i, x)] = out\n",
" return dp[(i, x)]\n",
"\n",
"arr = []\n",
"for x in test(0, gs, packages):\n",
" f = [z for y, z in zip(x, packages) if y]\n",
" if not test(0, gs, f):\n",
" continue\n",
" p = 1\n",
" for y in f:\n",
" p *= y\n",
" arr.append((len(f), p))\n",
"min(arr)[1]"
]
}
],
"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
}

99
Python/2015/25.ipynb Normal file
View file

@ -0,0 +1,99 @@
{
"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 = 2015, 25\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": [
"19980801"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import re\n",
"\n",
"row, col = map(int, re.match(r\"^.*?(\\d+).*?(\\d+).*?$\", puzzle).groups())\n",
"\n",
"n = (row + col - 2)\n",
"(20151125 * pow(252533, n * (n + 1) // 2 + 1 + col - 2, 33554393)) % 33554393"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"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
}

135
Python/2016/01.ipynb Normal file
View file

@ -0,0 +1,135 @@
{
"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
}

129
Python/2016/02.ipynb Normal file
View file

@ -0,0 +1,129 @@
{
"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
}

112
Python/2016/03.ipynb Normal file
View file

@ -0,0 +1,112 @@
{
"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
}

116
Python/2016/04.ipynb Normal file
View file

@ -0,0 +1,116 @@
{
"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
}

119
Python/2016/05.ipynb Normal file
View file

@ -0,0 +1,119 @@
{
"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
}

103
Python/2016/06.ipynb Normal file
View file

@ -0,0 +1,103 @@
{
"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
}

155
Python/2016/07.ipynb Normal file
View file

@ -0,0 +1,155 @@
{
"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
}

130
Python/2016/08.ipynb Normal file
View file

@ -0,0 +1,130 @@
{
"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
}

136
Python/2016/09.ipynb Normal file
View file

@ -0,0 +1,136 @@
{
"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
}

162
Python/2016/10.ipynb Normal file
View file

@ -0,0 +1,162 @@
{
"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
}

183
Python/2016/11.ipynb Normal file
View file

@ -0,0 +1,183 @@
{
"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
}

133
Python/2016/12.ipynb Normal file
View file

@ -0,0 +1,133 @@
{
"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
}

141
Python/2016/13.ipynb Normal file
View file

@ -0,0 +1,141 @@
{
"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
}

152
Python/2016/14.ipynb Normal file
View file

@ -0,0 +1,152 @@
{
"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
}

119
Python/2016/15.ipynb Normal file
View file

@ -0,0 +1,119 @@
{
"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
}

120
Python/2016/16.ipynb Normal file
View file

@ -0,0 +1,120 @@
{
"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
}

151
Python/2016/17.ipynb Normal file
View file

@ -0,0 +1,151 @@
{
"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
}

123
Python/2016/18.ipynb Normal file
View file

@ -0,0 +1,123 @@
{
"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
}

115
Python/2016/19.ipynb Normal file
View file

@ -0,0 +1,115 @@
{
"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
}

129
Python/2016/20.ipynb Normal file
View file

@ -0,0 +1,129 @@
{
"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
}

137
Python/2016/21.ipynb Normal file
View file

@ -0,0 +1,137 @@
{
"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
}

156
Python/2016/22.ipynb Normal file
View file

@ -0,0 +1,156 @@
{
"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
}

149
Python/2016/23.ipynb Normal file
View file

@ -0,0 +1,149 @@
{
"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
}

163
Python/2016/24.ipynb Normal file
View file

@ -0,0 +1,163 @@
{
"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
}

118
Python/2016/25.ipynb Normal file
View file

@ -0,0 +1,118 @@
{
"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
}

149
Python/2017/01.ipynb Normal file
View file

@ -0,0 +1,149 @@
{
"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 = 2017, 1\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"995"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" return sum(int(a) for a, b in zip(puzzle, puzzle[1:] + puzzle[0]) if a == b)\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"229 µs ± 3.49 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1130"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve2():\n",
" n = len(puzzle) // 2\n",
" return sum(int(a) for a, b in zip(puzzle, puzzle[n:] + puzzle[:n]) if a == b)\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"238 µs ± 5.77 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

162
Python/2017/02.ipynb Normal file
View file

@ -0,0 +1,162 @@
{
"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 = 2017, 2\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"36174"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" s = 0\n",
" for line in plines:\n",
" nums = [*map(int, line.split())]\n",
" s += max(nums) - min(nums)\n",
" return s\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"68.7 µs ± 6.06 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"244"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve2():\n",
" s = 0\n",
" for line in plines:\n",
" nums = [*map(int, line.split())]\n",
" for a in nums:\n",
" for b in nums:\n",
" if a % b == 0 and a != b:\n",
" s += a // b\n",
" break\n",
" else: continue\n",
" break\n",
" return s\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"291 µs ± 89.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

177
Python/2017/03.ipynb Normal file
View file

@ -0,0 +1,177 @@
{
"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 = 2017, 3\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"430"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" num = int(puzzle)\n",
" i = (int((num-1) ** .5)+1) // 2\n",
" a, b = (i*2-1)**2, (i*2+1)**2\n",
" out = 1e1337\n",
" for j in range(4):\n",
" t = j / 4 + .125\n",
" out = min(out, abs(num-int((1-t)*a+t*b)))\n",
" return out + i\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4.23 µs ± 1.05 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"312453"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def iter_steps():\n",
" x, y = 0, 0\n",
" dx, dy = 1, 0\n",
" s = 0\n",
" i = 1\n",
" while True:\n",
" yield x, y\n",
" i += 1\n",
" x += dx\n",
" y += dy\n",
"\n",
" if i >= (s*2+1)**2:\n",
" s += 1\n",
" if abs(x + dx) > s or abs(y + dy) > s:\n",
" dx, dy = dy, -dx\n",
" \n",
"def solve2():\n",
" grid = {}\n",
" k = int(puzzle)\n",
" for x, y in iter_steps():\n",
" s = sum(grid.get((x+i,y+j), 0) for i in [-1,0,1] for j in [-1,0,1] if i or j) or 1\n",
" grid[(x,y)] = s\n",
" if s > k:\n",
" return s\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"293 µs ± 57.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

156
Python/2017/04.ipynb Normal file
View file

@ -0,0 +1,156 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"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 = 2017, 4\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"466"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" out = 0\n",
" for pw in plines:\n",
" x = pw.split()\n",
" out += len(set(x)) == len(x)\n",
" return out\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"809 µs ± 113 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"251"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve2():\n",
" out = 0\n",
" for pw in plines:\n",
" x = [\"\".join(sorted(e)) for e in pw.split()]\n",
" out += len(set(x)) == len(x)\n",
" return out\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4.79 ms ± 2.03 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

167
Python/2017/05.ipynb Normal file
View file

@ -0,0 +1,167 @@
{
"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 = 2017, 5\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"376976"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" jumps = [*map(int, plines)]\n",
" pos = 0\n",
" i = 0\n",
" while pos in range(len(jumps)):\n",
" p = pos\n",
" pos += jumps[pos]\n",
" jumps[p] += 1\n",
" i += 1\n",
" return i\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"244 ms ± 25.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"29227751"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve2():\n",
" jumps = [*map(int, plines)]\n",
" pos = 0\n",
" i = 0\n",
" while pos in range(len(jumps)):\n",
" p = pos\n",
" pos += jumps[pos]\n",
" if jumps[p] >= 3:\n",
" jumps[p] -= 1\n",
" else:\n",
" jumps[p] += 1\n",
" i += 1\n",
" return i\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"21.8 s ± 2.56 s per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

177
Python/2017/06.ipynb Normal file
View file

@ -0,0 +1,177 @@
{
"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 = 2017, 6\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"6681"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" nums = [*map(int, puzzle.split())]\n",
" seen = set()\n",
" out = 0\n",
" while tuple(nums) not in seen:\n",
" seen.add(tuple(nums))\n",
" idx = nums.index(max(nums))\n",
" n = nums[idx]\n",
" nums[idx] = 0\n",
" i = idx\n",
" for _ in range(n):\n",
" i = (i+1)%len(nums)\n",
" nums[i] += 1\n",
" out += 1 \n",
" \n",
" return out\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"40.8 ms ± 6.92 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2392"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve2():\n",
" nums = [*map(int, puzzle.split())]\n",
" seen = {}\n",
" out = 0\n",
" while tuple(nums) not in seen:\n",
" seen[tuple(nums)] = out\n",
" idx = nums.index(max(nums))\n",
" n = nums[idx]\n",
" nums[idx] = 0\n",
" i = idx\n",
" for _ in range(n):\n",
" i = (i+1)%len(nums)\n",
" nums[i] += 1\n",
" out += 1\n",
" \n",
" return out - seen[tuple(nums)]\n",
"\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"52.8 ms ± 20 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

182
Python/2017/07.ipynb Normal file
View file

@ -0,0 +1,182 @@
{
"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 = 2017, 7\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'uownj'"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" names = set()\n",
" subs = set()\n",
" for line in plines:\n",
" name = line.split()[0]\n",
" sub = [] if \"->\" not in line else line.split(\"-> \")[1].split(\", \")\n",
" names.add(name)\n",
" subs.update(sub)\n",
" return next(iter(names - subs))\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1.21 ms ± 168 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(596, None)"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve2():\n",
" progs = {}\n",
" names = set()\n",
" subs = set()\n",
" for line in plines:\n",
" name = line.split()[0]\n",
" weight = int(line.split(\"(\")[1].split(\")\")[0])\n",
" sub = [] if \"->\" not in line else line.split(\"-> \")[1].split(\", \")\n",
" progs[name] = weight, sub\n",
" names.add(name)\n",
" subs.update(sub)\n",
" root = next(iter(names - subs))\n",
" \n",
" def check_sum(p):\n",
" s = progs[p][0]\n",
" w = {}\n",
" for q in progs[p][1]:\n",
" a, b = check_sum(q)\n",
" if a is not None: return a, None\n",
" s += b\n",
" w[q] = b\n",
" \n",
" x = max(w.values(), key=list(w.values()).count, default=None)\n",
" for k, v in w.items():\n",
" if v != x:\n",
" return x - (v - progs[k][0]), None\n",
" return None, s\n",
" \n",
" return check_sum(root)\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5.44 ms ± 1.85 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

162
Python/2017/08.ipynb Normal file
View file

@ -0,0 +1,162 @@
{
"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 = 2017, 8\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3880"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" registers = {}\n",
" for line in plines:\n",
" reg, op, n, _, a, b, c = line.split()\n",
" if eval(str(registers.get(a, 0))+b+c):\n",
" x = registers.get(reg, 0)\n",
" registers[reg] = x + (-1 if op == \"dec\" else 1) * int(n)\n",
" return max(registers.values())\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"8.48 ms ± 1.42 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"5035"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve2():\n",
" registers = {}\n",
" out = 0\n",
" for line in plines:\n",
" reg, op, n, _, a, b, c = line.split()\n",
" if eval(str(registers.get(a, 0))+b+c):\n",
" x = registers.get(reg, 0)\n",
" registers[reg] = x + (-1 if op == \"dec\" else 1) * int(n)\n",
" out = max(out, registers[reg])\n",
" return out\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"10.2 ms ± 1.81 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

191
Python/2017/09.ipynb Normal file
View file

@ -0,0 +1,191 @@
{
"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 = 2017, 9\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"9251"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" out = 0\n",
" level = 0\n",
" garbage = False\n",
" skip = False\n",
" for c in puzzle:\n",
" if skip:\n",
" skip = False\n",
" continue\n",
" if garbage:\n",
" if c == \"!\":\n",
" skip = True\n",
" elif c == \">\":\n",
" garbage = False\n",
" else:\n",
" if c == \"{\":\n",
" level += 1\n",
" elif c == \"}\":\n",
" out += level\n",
" level -= 1\n",
" elif c == \"<\":\n",
" garbage = True\n",
" return out\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1.41 ms ± 102 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"4322"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve2():\n",
" out = 0\n",
" level = 0\n",
" garbage = False\n",
" skip = False\n",
" for c in puzzle:\n",
" if skip:\n",
" skip = False\n",
" continue\n",
" if garbage:\n",
" if c == \"!\":\n",
" skip = True\n",
" elif c == \">\":\n",
" garbage = False\n",
" else:\n",
" out += 1\n",
" else:\n",
" if c == \"{\":\n",
" level += 1\n",
" elif c == \"}\":\n",
" level -= 1\n",
" elif c == \"<\":\n",
" garbage = True\n",
" return out\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1.7 ms ± 178 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

187
Python/2017/10.ipynb Normal file
View file

@ -0,0 +1,187 @@
{
"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 = 2017, 10\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"20056"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" nums = [*range(256)]\n",
" pos = 0\n",
" skip = 0\n",
" \n",
" def rev(a, b):\n",
" a %= len(nums)\n",
" b = (b - a) % len(nums)\n",
" nums[:] = nums[a:] + nums[:a]\n",
" nums[:b] = nums[:b][::-1]\n",
" nums[:] = nums[-a:] + nums[:-a]\n",
" \n",
" for length in map(int, puzzle.split(\",\")):\n",
" rev(pos, pos + length)\n",
" pos += length + skip\n",
" skip += 1\n",
" return nums[0] * nums[1]\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"414 µs ± 123 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'d9a7de4a809c56bf3a9465cb84392c8e'"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve2():\n",
" lengths = [*map(ord, puzzle), 17, 31, 73, 47, 23]\n",
" nums = [*range(256)]\n",
" pos = 0\n",
" skip = 0\n",
" \n",
" def rev(a, b):\n",
" a %= len(nums)\n",
" b = (b - a) % len(nums)\n",
" nums[:] = nums[a:] + nums[:a]\n",
" nums[:b] = nums[:b][::-1]\n",
" nums[:] = nums[-a:] + nums[:-a]\n",
" \n",
" for _ in range(64):\n",
" for length in lengths:\n",
" rev(pos, pos + length)\n",
" pos += length + skip\n",
" skip += 1\n",
" \n",
" dense = []\n",
" for i in range(16):\n",
" x = 0\n",
" for j in range(16): x ^= nums[i*16+j]\n",
" dense.append(x)\n",
" \n",
" return \"\".join(f\"{x:02x}\" for x in dense)\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"60.4 ms ± 10.9 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

180
Python/2017/11.ipynb Normal file
View file

@ -0,0 +1,180 @@
{
"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 = 2017, 11\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"796"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def step(x, y, d):\n",
" if d == \"n\":\n",
" return x, y-1 # (0, -1)\n",
" if d == \"ne\":\n",
" return x+1, y # (1, 0)\n",
" if d == \"se\":\n",
" return x+1, y+1 # (1, 1)\n",
" if d == \"s\":\n",
" return x, y+1 # (0, 1)\n",
" if d == \"sw\":\n",
" return x-1, y # (-1, 0)\n",
" if d == \"nw\":\n",
" return x-1, y-1 # (-1, -1)\n",
"\n",
"def solve1():\n",
" x, y = 0, 0\n",
" for d in puzzle.split(\",\"):\n",
" x, y = step(x, y, d)\n",
" k = 0\n",
" if x * y > 0:\n",
" k = min(x, y, key=abs)\n",
" x -= k\n",
" y -= k\n",
" return abs(x) + abs(y) + k\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4.47 ms ± 1.33 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1585"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve2():\n",
" x, y = 0, 0\n",
" out = 0\n",
" for d in puzzle.split(\",\"):\n",
" x, y = step(x, y, d)\n",
" k = 0\n",
" if x * y > 0:\n",
" k = min(x, y, key=abs)\n",
" x -= k\n",
" y -= k\n",
" out = max(out, abs(x) + abs(y) + k)\n",
" return out\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"9.17 ms ± 1.72 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

190
Python/2017/12.ipynb Normal file
View file

@ -0,0 +1,190 @@
{
"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 = 2017, 12\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"283"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" edges = {}\n",
" for line in plines:\n",
" p, Q = line.split(\" <-> \")\n",
" p = int(p)\n",
" for q in map(int, Q.split(\", \")):\n",
" edges.setdefault(p, []).append(q)\n",
"\n",
" queue = [0]\n",
" visited = set()\n",
" while queue:\n",
" p = queue.pop(0)\n",
" \n",
" if p in visited: continue\n",
" visited.add(p)\n",
" \n",
" for q in edges.get(p, []):\n",
" queue.append(q)\n",
" \n",
" return len(visited)\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3.37 ms ± 189 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"195"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"class UnionFind:\n",
" def __init__(self, n):\n",
" self.parents = list(range(n))\n",
" \n",
" def find(self, x):\n",
" if self.parents[x] == x: return x\n",
" out = self.find(self.parents[x])\n",
" self.parents[x] = out\n",
" return out\n",
" \n",
" def merge(self, a, b):\n",
" a = self.find(a)\n",
" b = self.find(b)\n",
" self.parents[a] = b\n",
"\n",
"def solve2():\n",
" uf = UnionFind(len(plines))\n",
" for line in plines:\n",
" p, Q = line.split(\" <-> \")\n",
" p = int(p)\n",
" for q in map(int, Q.split(\", \")):\n",
" uf.merge(p, q)\n",
"\n",
" groups = set()\n",
" for i in range(len(plines)): groups.add(uf.find(i))\n",
" return len(groups)\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"9.59 ms ± 787 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

178
Python/2017/13.ipynb Normal file
View file

@ -0,0 +1,178 @@
{
"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 = 2017, 13\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1928"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" R = {}\n",
" S = {}\n",
" for line in plines:\n",
" a, b = map(int, line.split(\": \"))\n",
" R[a] = b\n",
" S[a] = 0\n",
" \n",
" n = max(S)\n",
" out = 0\n",
" for i in range(n):\n",
" if i in S and S[i] == 0:\n",
" out += i * R[i]\n",
" for k, v in S.items():\n",
" S[k] = (v + 1) % (R[k] * 2 - 2)\n",
" return out\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1.15 ms ± 145 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3830344"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def step(R, S):\n",
" for k, v in S.items():\n",
" S[k] = (v + 1) % (R[k] * 2 - 2)\n",
"\n",
"def solve2():\n",
" R = {}\n",
" SC = {}\n",
" for line in plines:\n",
" a, b = map(int, line.split(\": \"))\n",
" R[a] = b\n",
" SC[a] = 0\n",
" n = max(SC)\n",
" \n",
" def test():\n",
" S = SC.copy()\n",
" for i in range(n+1):\n",
" if i in S and S[i] == 0:\n",
" return False\n",
" step(R, S)\n",
" return True\n",
" \n",
" k = 0\n",
" while not test():\n",
" k += 1\n",
" step(R, SC)\n",
" return k\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%timeit solve2()"
]
}
],
"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
}

216
Python/2017/14.ipynb Normal file
View file

@ -0,0 +1,216 @@
{
"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 = 2017, 14\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"def knot(inp):\n",
" lengths = [*map(ord, inp), 17, 31, 73, 47, 23]\n",
" nums = [*range(256)]\n",
" pos = 0\n",
" skip = 0\n",
" \n",
" def rev(a, b):\n",
" a %= len(nums)\n",
" b = (b - a) % len(nums)\n",
" nums[:] = nums[a:] + nums[:a]\n",
" nums[:b] = nums[:b][::-1]\n",
" nums[:] = nums[-a:] + nums[:-a]\n",
" \n",
" for _ in range(64):\n",
" for length in lengths:\n",
" rev(pos, pos + length)\n",
" pos += length + skip\n",
" skip += 1\n",
" \n",
" dense = []\n",
" for i in range(16):\n",
" x = 0\n",
" for j in range(16): x ^= nums[i*16+j]\n",
" dense.append(x)\n",
" \n",
" return \"\".join(f\"{x:02x}\" for x in dense)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"8292"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" out = 0\n",
" for i in range(128):\n",
" k = bin(int(knot(f\"{puzzle}-{i}\"), 16))[2:].zfill(128)\n",
" out += k.count(\"1\")\n",
" return out\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2.09 s ± 177 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1069"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"class UnionFind:\n",
" def __init__(self, n):\n",
" self.parents = list(range(n))\n",
" \n",
" def find(self, x):\n",
" if self.parents[x] == x: return x\n",
" out = self.find(self.parents[x])\n",
" self.parents[x] = out\n",
" return out\n",
" \n",
" def merge(self, a, b):\n",
" a = self.find(a)\n",
" b = self.find(b)\n",
" self.parents[a] = b\n",
"\n",
"def solve2():\n",
" last = None\n",
" uf = UnionFind(128 * 128)\n",
" free = 0\n",
" for i in range(128):\n",
" k = bin(int(knot(f\"{puzzle}-{i}\"), 16))[2:].zfill(128)\n",
" for j in range(128):\n",
" if k[j] != \"1\":\n",
" free += 1\n",
" continue\n",
" if i and last[j] == \"1\": uf.merge((i-1)*128+j, i*128+j)\n",
" if j and k[j-1] == \"1\": uf.merge(i*128+j-1, i*128+j)\n",
" last = k\n",
" \n",
" groups = set()\n",
" for i in range(128*128): groups.add(uf.find(i))\n",
" return len(groups) - free\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2.49 s ± 467 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

141
Python/2017/15.ipynb Normal file
View file

@ -0,0 +1,141 @@
{
"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 = 2017, 15\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"650"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def gen(prev, k):\n",
" return (prev * k) % 2147483647\n",
"\n",
"def solve1():\n",
" a, b = [int(line.split()[-1]) for line in plines]\n",
" out = 0\n",
" M = 1 << 16\n",
" for _ in range(40000000):\n",
" a = gen(a, 16807)\n",
" b = gen(b, 48271)\n",
" out += a % M == b % M\n",
" return out\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def generate(x, k, m):\n",
" while True:\n",
" x = gen(x, k)\n",
" if x % m == 0: yield x\n",
"\n",
"def solve2():\n",
" a, b = [int(line.split()[-1]) for line in plines]\n",
" out = 0\n",
" M = 1 << 16\n",
" for _, a, b in zip(range(5000000), generate(a, 16807, 4), generate(b, 48271, 8)):\n",
" out += a % M == b % M\n",
" return out\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%timeit solve2()"
]
}
],
"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
}

177
Python/2017/16.ipynb Normal file
View file

@ -0,0 +1,177 @@
{
"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 = 2017, 16\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'kbednhopmfcjilag'"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" p = [chr(97 + i) for i in range(16)]\n",
" for cmd in puzzle.split(\",\"):\n",
" if cmd[0] == \"s\":\n",
" n = int(cmd[1:])\n",
" p = p[-n:] + p[:-n]\n",
" elif cmd[0] == \"x\":\n",
" a, b = map(int, cmd[1:].split(\"/\"))\n",
" p[a], p[b] = p[b], p[a]\n",
" elif cmd[0] == \"p\":\n",
" a, b = map(p.index, cmd[1:].split(\"/\"))\n",
" p[a], p[b] = p[b], p[a]\n",
" \n",
" return \"\".join(p)\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"11.7 ms ± 959 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'fbmcgdnjakpioelh'"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve2():\n",
" p = [chr(97 + i) for i in range(16)]\n",
" q = p[:]\n",
" mem = []\n",
" while True:\n",
" mem.append(p[:])\n",
" for cmd in puzzle.split(\",\"):\n",
" if cmd[0] == \"s\":\n",
" n = int(cmd[1:])\n",
" p = p[-n:] + p[:-n]\n",
" elif cmd[0] == \"x\":\n",
" a, b = map(int, cmd[1:].split(\"/\"))\n",
" p[a], p[b] = p[b], p[a]\n",
" elif cmd[0] == \"p\":\n",
" a, b = map(p.index, cmd[1:].split(\"/\"))\n",
" p[a], p[b] = p[b], p[a]\n",
" if p == q: break\n",
" \n",
" return \"\".join(mem[1000000000 % len(mem)])\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"687 ms ± 72.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

160
Python/2017/17.ipynb Normal file
View file

@ -0,0 +1,160 @@
{
"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 = 2017, 17\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"808"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" n = int(puzzle)\n",
" lst = [0]\n",
" pos = 0\n",
" for i in range(1, 2018):\n",
" pos = (pos + n) % len(lst) + 1\n",
" lst.insert(pos, i)\n",
" return lst[(lst.index(2017)+1)%len(lst)]\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1.35 ms ± 379 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"47465686"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve2():\n",
" k = int(puzzle)\n",
" i = 0\n",
" last = None\n",
" for j in range(1, 50000000+1):\n",
" i = (i + k) % j + 1\n",
" if i == 1: last = j\n",
" return last\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"9.62 s ± 1.52 s per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

210
Python/2017/18.ipynb Normal file
View file

@ -0,0 +1,210 @@
{
"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 = 2017, 18\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"4601"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" registers = {}\n",
" lp = None\n",
" pc = 0\n",
" while pc in range(len(plines)):\n",
" cmd, *args = plines[pc].split()\n",
" get = lambda a: int(a) if a.removeprefix(\"-\").isnumeric() else registers.setdefault(a, 0)\n",
" if cmd == \"snd\":\n",
" lp = get(args[0])\n",
" elif cmd == \"set\":\n",
" registers[args[0]] = get(args[1])\n",
" elif cmd == \"add\":\n",
" registers[args[0]] = get(args[0]) + get(args[1])\n",
" elif cmd == \"mul\":\n",
" registers[args[0]] = get(args[0]) * get(args[1])\n",
" elif cmd == \"mod\":\n",
" registers[args[0]] = get(args[0]) % get(args[1])\n",
" elif cmd == \"rcv\":\n",
" if get(args[0]):\n",
" return lp\n",
" elif cmd == \"jgz\":\n",
" if get(args[0]) > 0:\n",
" pc += get(args[1])\n",
" continue\n",
" \n",
" pc += 1\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2.76 ms ± 304 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"6858"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"class VM:\n",
" def __init__(self, p):\n",
" self.registers = {\"p\": p}\n",
" self.pc = 0\n",
" self.inp = []\n",
" self.msg = None\n",
" self.cnt = 0\n",
" \n",
" def step(self):\n",
" if self.pc not in range(len(plines)): return False\n",
" cmd, *args = plines[self.pc].split()\n",
" get = lambda a: int(a) if a.removeprefix(\"-\").isnumeric() else self.registers.setdefault(a, 0)\n",
" if cmd == \"snd\":\n",
" self.cnt += 1\n",
" self.msg(get(args[0]))\n",
" elif cmd == \"set\":\n",
" self.registers[args[0]] = get(args[1])\n",
" elif cmd == \"add\":\n",
" self.registers[args[0]] = get(args[0]) + get(args[1])\n",
" elif cmd == \"mul\":\n",
" self.registers[args[0]] = get(args[0]) * get(args[1])\n",
" elif cmd == \"mod\":\n",
" self.registers[args[0]] = get(args[0]) % get(args[1])\n",
" elif cmd == \"rcv\":\n",
" if not self.inp: return False\n",
" self.registers[args[0]] = self.inp.pop(0)\n",
" elif cmd == \"jgz\":\n",
" if get(args[0]) > 0:\n",
" self.pc += get(args[1])\n",
" return True\n",
" self.pc += 1\n",
" return True\n",
"\n",
"def solve2():\n",
" p0 = VM(0)\n",
" p1 = VM(1)\n",
" p0.msg = p1.inp.append\n",
" p1.msg = p0.inp.append\n",
" while p0.step() + p1.step(): pass\n",
" return p1.cnt\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"373 ms ± 180 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

194
Python/2017/19.ipynb Normal file
View file

@ -0,0 +1,194 @@
{
"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 = 2017, 19\n",
"\n",
"puzzle = aoc.setup(year, day, strip=False)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'MOABEUCWQS'"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" w, h = len(plines[0]), len(plines)\n",
" x, y = plines[0].index(\"|\"), 0\n",
" dx, dy = 0, 1\n",
" out = \"\"\n",
" get = lambda x, y: plines[y][x] if y in range(h) and x in range(w) else \" \"\n",
" while True:\n",
" c = get(x, y)\n",
" f = get(x+dx, y+dy)\n",
" l = get(x+dy, y-dx)\n",
" r = get(x-dy, y+dx)\n",
" if c.isalpha():\n",
" out += c\n",
" \n",
" if f == \" \":\n",
" if l != \" \":\n",
" dx, dy = dy, -dx\n",
" elif r != \" \":\n",
" dx, dy = -dy, dx\n",
" else:\n",
" break\n",
"\n",
" x += dx\n",
" y += dy\n",
" \n",
" return out\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"66.6 ms ± 14.3 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"18058"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve2():\n",
" w, h = len(plines[0]), len(plines)\n",
" x, y = plines[0].index(\"|\"), 0\n",
" dx, dy = 0, 1\n",
" out = 0\n",
" get = lambda x, y: plines[y][x] if y in range(h) and x in range(w) else \" \"\n",
" while True:\n",
" out += 1\n",
" f = get(x+dx, y+dy)\n",
" l = get(x+dy, y-dx)\n",
" r = get(x-dy, y+dx)\n",
" \n",
" if f == \" \":\n",
" if l != \" \":\n",
" dx, dy = dy, -dx\n",
" elif r != \" \":\n",
" dx, dy = -dy, dx\n",
" else:\n",
" break\n",
"\n",
" x += dx\n",
" y += dy\n",
" \n",
" return out\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"41.2 ms ± 1.32 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

187
Python/2017/20.ipynb Normal file
View file

@ -0,0 +1,187 @@
{
"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 = 2017, 20\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"258"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" n = 0\n",
" p = []\n",
" v = []\n",
" a = []\n",
" for line in plines:\n",
" x, y, z = [tuple(map(int, k.split(\"<\")[1].strip(\">\").split(\",\"))) for k in line.split(\", \")]\n",
" p.append(x)\n",
" v.append(y)\n",
" a.append(z)\n",
" n += 1\n",
" \n",
" for _ in range(2000):\n",
" for i in range(n):\n",
" v[i] = v[i][0]+a[i][0], v[i][1]+a[i][1], v[i][2]+a[i][2]\n",
" p[i] = v[i][0]+p[i][0], v[i][1]+p[i][1], v[i][2]+p[i][2]\n",
" \n",
" return min(range(n), key=lambda i: sum(map(abs, p[i])))\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2.57 s ± 151 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"707"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve2():\n",
" p = []\n",
" v = []\n",
" a = []\n",
" for line in plines:\n",
" x, y, z = [tuple(map(int, k.split(\"<\")[1].strip(\">\").split(\",\"))) for k in line.split(\", \")]\n",
" p.append(x)\n",
" v.append(y)\n",
" a.append(z)\n",
" \n",
" pos = lambda i, t: tuple(\n",
" p[i][k] + t*v[i][k] + t*(t+1)//2*a[i][k]\n",
" for k in range(3)\n",
" )\n",
" \n",
" alive = set(range(len(p)))\n",
" for t in range(1000):\n",
" s = {}\n",
" for i in alive:\n",
" s.setdefault(pos(i, t), []).append(i)\n",
" for y, x in s.items():\n",
" if len(x) > 1:\n",
" alive.difference_update(x)\n",
" \n",
" return len(alive)\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2.27 s ± 219 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

209
Python/2017/21.ipynb Normal file
View file

@ -0,0 +1,209 @@
{
"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 = 2017, 21\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"197"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def rotate(p):\n",
" return tuple(\"\".join(p[j][i] for j in range(len(p))) for i in reversed(range(len(p[0]))))\n",
"\n",
"def solve1():\n",
" rules = {}\n",
" pattern = \".#.\", \"..#\", \"###\"\n",
" for line in plines:\n",
" a, b = [tuple(k.split(\"/\")) for k in line.split(\" => \")]\n",
" rules[a] = b\n",
" \n",
" def find_rule(p):\n",
" for _ in range(4):\n",
" if p in rules: return rules[p]\n",
" p = rotate(p)\n",
" p = tuple(reversed(p))\n",
" for _ in range(4):\n",
" if p in rules: return rules[p]\n",
" p = rotate(p)\n",
" \n",
" def apply():\n",
" k = 3 if len(pattern) % 2 else 2\n",
" out = []\n",
" for i in range(len(pattern)//k):\n",
" b = []\n",
" for j in range(len(pattern)//k):\n",
" new = find_rule(tuple(\"\".join(pattern[i*k+y][j*k+x] for x in range(k)) for y in range(k)))\n",
" b.append(new)\n",
" for line in zip(*b):\n",
" out.append(\"\".join(line))\n",
" return tuple(out)\n",
" \n",
" for _ in range(5):\n",
" pattern = apply()\n",
" return sum(line.count(\"#\") for line in pattern)\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"804 µs ± 63.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3081737"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve2():\n",
" rules = {}\n",
" pattern = \".#.\", \"..#\", \"###\"\n",
" for line in plines:\n",
" a, b = [tuple(k.split(\"/\")) for k in line.split(\" => \")]\n",
" rules[a] = b\n",
" \n",
" def find_rule(p):\n",
" for _ in range(4):\n",
" if p in rules: return rules[p]\n",
" p = rotate(p)\n",
" p = tuple(reversed(p))\n",
" for _ in range(4):\n",
" if p in rules: return rules[p]\n",
" p = rotate(p)\n",
" \n",
" def apply():\n",
" k = 3 if len(pattern) % 2 else 2\n",
" out = []\n",
" for i in range(len(pattern)//k):\n",
" b = []\n",
" for j in range(len(pattern)//k):\n",
" new = find_rule(tuple(\"\".join(pattern[i*k+y][j*k+x] for x in range(k)) for y in range(k)))\n",
" b.append(new)\n",
" for line in zip(*b):\n",
" out.append(\"\".join(line))\n",
" return tuple(out)\n",
" \n",
" for _ in range(18):\n",
" pattern = apply()\n",
" return sum(line.count(\"#\") for line in pattern)\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"9.14 s ± 331 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

194
Python/2017/22.ipynb Normal file
View file

@ -0,0 +1,194 @@
{
"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 = 2017, 22\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"5256"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" infected = set()\n",
" x, y = len(plines[0])//2, len(plines)//2\n",
" dx, dy = 0, -1\n",
" out = 0\n",
" for i, line in enumerate(plines):\n",
" for j, c in enumerate(line):\n",
" if c == \"#\":\n",
" infected.add((j, i))\n",
" for _ in range(10000):\n",
" inf = (x, y) in infected\n",
" if inf:\n",
" dx, dy = -dy, dx\n",
" infected.remove((x, y))\n",
" else:\n",
" dx, dy = dy, -dx\n",
" infected.add((x, y))\n",
" out += 1\n",
" \n",
" x += dx\n",
" y += dy\n",
" \n",
" return out\n",
" \n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5.3 ms ± 448 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2511345"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve2():\n",
" state = {}\n",
" x, y = len(plines[0])//2, len(plines)//2\n",
" dx, dy = 0, -1\n",
" out = 0\n",
" for i, line in enumerate(plines):\n",
" for j, c in enumerate(line):\n",
" if c == \"#\":\n",
" state[(j, i)] = 2\n",
" for _ in range(10000000):\n",
" s = state.get((x, y), 0)\n",
" \n",
" if s == 0: dx, dy = dy, -dx\n",
" elif s == 2: dx, dy = -dy, dx\n",
" elif s == 3: dx, dy = -dx, -dy\n",
" \n",
" if s == 1: out += 1\n",
"\n",
" if s == 3:\n",
" state.pop((x, y))\n",
" else:\n",
" state[(x, y)] = s + 1\n",
" \n",
" x += dx\n",
" y += dy\n",
" \n",
" return out\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"8.54 s ± 433 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

289
Python/2017/23.ipynb Normal file
View file

@ -0,0 +1,289 @@
{
"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 = 2017, 23\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"9409"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" registers = {chr(i): 0 for i in range(97, 105)}\n",
" pc = 0\n",
" out = 0\n",
" while pc in range(len(plines)):\n",
" cmd, *args = plines[pc].split()\n",
" get = lambda a: registers[a] if a in registers else int(a)\n",
" if cmd == \"set\":\n",
" registers[args[0]] = get(args[1])\n",
" elif cmd == \"sub\":\n",
" registers[args[0]] -= get(args[1])\n",
" elif cmd == \"mul\":\n",
" registers[args[0]] *= get(args[1])\n",
" out += 1\n",
" elif cmd == \"jnz\":\n",
" if get(args[0]):\n",
" pc += get(args[1])\n",
" continue\n",
" pc += 1\n",
" \n",
" return out\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"134 ms ± 19 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"001| b = 99\n",
"002| c = b\n",
"003| if a: goto 005\n",
"004| goto 009\n",
"\n",
"# jumps: 003\n",
"005| b *= 100\n",
"006| b += 100000\n",
"007| c = b\n",
"008| c += 17000\n",
"\n",
"# jumps: 004, 032\n",
"009| f = 1\n",
"010| d = 2\n",
"\n",
"# jumps: 024\n",
"011| e = 2\n",
"\n",
"# jumps: 020\n",
"012| g = d\n",
"013| g *= e\n",
"014| g -= b\n",
"015| if g: goto 017\n",
"016| f = 0\n",
"\n",
"# jumps: 015\n",
"017| e += 1\n",
"018| g = e\n",
"019| g -= b\n",
"020| if g: goto 012\n",
"021| d += 1\n",
"022| g = d\n",
"023| g -= b\n",
"024| if g: goto 011\n",
"025| if f: goto 027\n",
"026| h += 1\n",
"\n",
"# jumps: 025\n",
"027| g = b\n",
"028| g -= c\n",
"029| if g: goto 031\n",
"030| goto 033\n",
"\n",
"# jumps: 029\n",
"031| b += 17\n",
"032| goto 009\n"
]
}
],
"source": [
"jumps = {}\n",
"out = []\n",
"for i, line in enumerate(plines):\n",
" cmd, *args = line.split()\n",
" if cmd == \"set\":\n",
" out.append(f\"{args[0]} = {args[1]}\")\n",
" elif cmd == \"sub\":\n",
" if args[1].strip(\"-\").isnumeric() and int(args[1]) < 0:\n",
" out.append(f\"{args[0]} += {-int(args[1])}\")\n",
" else:\n",
" out.append(f\"{args[0]} -= {args[1]}\")\n",
" elif cmd == \"mul\":\n",
" out.append(f\"{args[0]} *= {args[1]}\")\n",
" elif cmd == \"jnz\":\n",
" x, y = args\n",
" y = i + int(y)\n",
" if x == \"0\":\n",
" out.append(\"noop\")\n",
" continue\n",
" elif x.strip(\"-\").isnumeric():\n",
" out.append(f\"goto {y+1:03}\")\n",
" else:\n",
" out.append(f\"if {x}: goto {y+1:03}\")\n",
" jumps.setdefault(y, []).append(f\"{i+1:03}\")\n",
" else:\n",
" out.append(\"noop\")\n",
" \n",
"\n",
"for i, line in enumerate(out):\n",
" if i in jumps: print(f\"\\n# jumps: {', '.join(jumps[i])}\")\n",
" print(f\"{i+1:03}| {line}\")"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"b = 109900 - 17\n",
"\n",
"while b != 126900 {\n",
" b += 17\n",
" \n",
" f = 1\n",
" for d in range(2, b):\n",
" if b % d == 0:\n",
" f = 0\n",
" \n",
" if f == 0: h += 1\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"913"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve2():\n",
" b = 109900 - 17\n",
" h = 0\n",
" while b != 126900:\n",
" b += 17\n",
"\n",
" f = 1\n",
" for d in range(2, b):\n",
" if b % d == 0:\n",
" f = 0\n",
" break\n",
"\n",
" if f == 0: h += 1\n",
" return h\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1.15 s ± 297 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

179
Python/2017/24.ipynb Normal file
View file

@ -0,0 +1,179 @@
{
"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 = 2017, 24\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1656"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" comps = sorted([tuple(sorted(map(int, line.split(\"/\")))) for line in plines])\n",
" used = set()\n",
" \n",
" def solve(port):\n",
" best = 0\n",
" for i, (p, q) in enumerate(comps):\n",
" if i in used: continue\n",
" if q == port: p, q = q, p\n",
" if p != port: continue\n",
" used.add(i)\n",
" best = max(best, p+q+solve(q))\n",
" used.remove(i)\n",
" return best\n",
" \n",
" \n",
" return solve(0)\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"7.62 s ± 409 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1642"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve2():\n",
" comps = sorted([tuple(sorted(map(int, line.split(\"/\")))) for line in plines])\n",
" used = set()\n",
" \n",
" def solve(port):\n",
" best = 0, 0\n",
" for i, (p, q) in enumerate(comps):\n",
" if i in used: continue\n",
" if q == port: p, q = q, p\n",
" if p != port: continue\n",
" used.add(i)\n",
" a, b = solve(q)\n",
" best = max(best, (a + 1, p+q+b))\n",
" used.remove(i)\n",
" return best\n",
" \n",
" \n",
" return solve(0)[1]\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"7.7 s ± 371 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

124
Python/2017/25.ipynb Normal file
View file

@ -0,0 +1,124 @@
{
"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 = 2017, 25\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"5593"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" state = plines[0].split()[-1].strip(\".\")\n",
" n = int(plines[1].split()[-2])\n",
" tm = {}\n",
" on = set()\n",
" p = 0\n",
"\n",
" for s in map(str.splitlines, puzzle.split(\"\\n\\n\")[1:]):\n",
" tm[s[0].split()[-1].strip(\":\")] = [\n",
" (\n",
" int(s[i*4+2].split()[-1].strip(\".\")),\n",
" -1 if s[i*4+3].split()[-1] == \"left.\" else 1,\n",
" s[i*4+4].split()[-1].strip(\".\")\n",
" )\n",
" for i in range(2)\n",
" ]\n",
" \n",
" for _ in range(n):\n",
" s = tm[state][p in on]\n",
" if s[0]: on.add(p)\n",
" else: on.discard(p)\n",
" p += s[1]\n",
" state = s[2]\n",
" \n",
" return len(on)\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5.49 s ± 546 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
}
],
"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
}

173
Python/2018/11.ipynb Normal file
View file

@ -0,0 +1,173 @@
{
"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 = 2018, 11\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'243,72'"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" serial = int(puzzle)\n",
" get = lambda x, y: ((((x+10)*y+serial)*(x+10))//100)%10 - 5\n",
" \n",
" return \",\".join(map(str, max(\n",
" ((x, y)\n",
" for x in range(1, 299)\n",
" for y in range(1, 299)),\n",
" key=lambda k: sum(get(k[0]+i, k[1]+j) for i in range(3) for j in range(3))\n",
" )))\n",
" \n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"560 ms ± 72.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'229,192,11'"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve2():\n",
" serial = int(puzzle)\n",
" get = lambda x, y: ((((x+10)*y+serial)*(x+10))//100)%10 - 5\n",
" ps = [[0] * 301]\n",
" for i in range(1, 301):\n",
" lst = [0]\n",
" for j in range(1, 301):\n",
" lst.append(get(j, i) + ps[i-1][j] + lst[j-1] - ps[i-1][j-1])\n",
" ps.append(lst)\n",
" \n",
" sq = lambda x, y, s: ps[y+s-1][x+s-1] - ps[y-1][x+s-1] - ps[y+s-1][x-1] + ps[y-1][x-1]\n",
" return \",\".join(map(str, max(\n",
" (\n",
" (i, j, s)\n",
" for s in range(1, 301)\n",
" for i in range(1, 302-s)\n",
" for j in range(1, 302-s)\n",
" ), key=lambda k: sq(*k)\n",
" )))\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"10.8 s ± 808 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

155
Python/2018/12.ipynb Normal file
View file

@ -0,0 +1,155 @@
{
"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 = 2018, 12\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3230"
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" state, _, *rules = plines\n",
" state = {i for i, x in enumerate(state.split()[-1]) if x == \"#\"}\n",
" rules = [x.split()[-1] == \"#\" for x in sorted(rules, reverse=True)]\n",
" \n",
" for _ in range(20):\n",
" nums = {k+i-2 for k in state for i in range(5)}\n",
" state = {\n",
" k\n",
" for k in nums\n",
" if rules[sum(((k+i-2) in state) * (2**(4-i)) for i in range(5))]\n",
" }\n",
" return sum(state)\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4400000000304\n"
]
}
],
"source": [
"def solve2():\n",
" state, _, *rules = plines\n",
" state = {i for i, x in enumerate(state.split()[-1]) if x == \"#\"}\n",
" rules = [x.split()[-1] == \"#\" for x in sorted(rules, reverse=True)]\n",
" \n",
" last = None\n",
" for _ in range(200):\n",
" nums = {k+i-2 for k in state for i in range(5)}\n",
" state = {\n",
" k\n",
" for k in nums\n",
" if rules[sum(((k+i-2) in state) * (2**(4-i)) for i in range(5))]\n",
" }\n",
" s = sum(state)\n",
" step = s - last if last is not None else None\n",
" last = s\n",
" print(s + step * (50000000000 - 200))\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%timeit solve2()"
]
}
],
"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
}

242
Python/2018/13.ipynb Normal file
View file

@ -0,0 +1,242 @@
{
"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 = 2018, 13\n",
"\n",
"puzzle = aoc.setup(year, day, strip=False)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'38,57'"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" carts = []\n",
" tracks = plines.copy()\n",
" positions = set()\n",
" for y, line in enumerate(tracks):\n",
" for x in range(len(line)):\n",
" c = line[x]\n",
" if c == \"^\":\n",
" carts.append([x, y, 0, -1, 0])\n",
" positions.add((x, y))\n",
" tracks[y] = line = line[:x] + \"|\" + line[x+1:]\n",
" elif c == \"v\":\n",
" carts.append([x, y, 0, 1, 0])\n",
" positions.add((x, y))\n",
" tracks[y] = line = line[:x] + \"|\" + line[x+1:]\n",
" elif c == \"<\":\n",
" carts.append([x, y, -1, 0, 0])\n",
" positions.add((x, y))\n",
" tracks[y] = line = line[:x] + \"-\" + line[x+1:]\n",
" elif c == \">\":\n",
" carts.append([x, y, 1, 0, 0])\n",
" positions.add((x, y))\n",
" tracks[y] = line = line[:x] + \"-\" + line[x+1:]\n",
" \n",
" while True:\n",
" for cart in sorted(carts, key=lambda c: (c[1], c[0])):\n",
" x, y, dx, dy, k = cart\n",
" positions.remove((x, y))\n",
" x += dx\n",
" y += dy\n",
" if (x, y) in positions:\n",
" return f\"{x},{y}\"\n",
" positions.add((x, y))\n",
" \n",
" if tracks[y][x] == \"/\":\n",
" dx, dy = -dy, -dx\n",
" elif tracks[y][x] == \"\\\\\":\n",
" dx, dy = dy, dx\n",
" elif tracks[y][x] == \"+\":\n",
" if k == 0: dx, dy = dy, -dx\n",
" elif k == 2: dx, dy = -dy, dx\n",
" k = (k + 1) % 3\n",
" \n",
" cart[:] = x, y, dx, dy, k\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"10.1 ms ± 1.24 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'4,92'"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve2():\n",
" carts = []\n",
" tracks = plines.copy()\n",
" positions = {}\n",
" crashed = set()\n",
" for y, line in enumerate(tracks):\n",
" for x in range(len(line)):\n",
" c = line[x]\n",
" if c == \"^\":\n",
" carts.append([x*len(tracks)+y, x, y, 0, -1, 0])\n",
" positions[(x, y)] = x*len(tracks)+y\n",
" tracks[y] = line = line[:x] + \"|\" + line[x+1:]\n",
" elif c == \"v\":\n",
" carts.append([x*len(tracks)+y, x, y, 0, 1, 0])\n",
" positions[(x, y)] = x*len(tracks)+y\n",
" tracks[y] = line = line[:x] + \"|\" + line[x+1:]\n",
" elif c == \"<\":\n",
" carts.append([x*len(tracks)+y, x, y, -1, 0, 0])\n",
" positions[(x, y)] = x*len(tracks)+y\n",
" tracks[y] = line = line[:x] + \"-\" + line[x+1:]\n",
" elif c == \">\":\n",
" carts.append([x*len(tracks)+y, x, y, 1, 0, 0])\n",
" positions[(x, y)] = x*len(tracks)+y\n",
" tracks[y] = line = line[:x] + \"-\" + line[x+1:]\n",
"\n",
" while True:\n",
" for cart in sorted(carts, key=lambda c: (c[2], c[1])):\n",
" i, x, y, dx, dy, k = cart\n",
" if i in crashed: continue\n",
" \n",
" positions.pop((x, y))\n",
" x += dx\n",
" y += dy\n",
" if (x, y) in positions:\n",
" crashed.add(i)\n",
" crashed.add(positions.pop((x, y)))\n",
" continue\n",
" positions[(x, y)] = i\n",
" \n",
" if tracks[y][x] == \"/\":\n",
" dx, dy = -dy, -dx\n",
" elif tracks[y][x] == \"\\\\\":\n",
" dx, dy = dy, dx\n",
" elif tracks[y][x] == \"+\":\n",
" if k == 0: dx, dy = dy, -dx\n",
" elif k == 2: dx, dy = -dy, dx\n",
" k = (k + 1) % 3\n",
" \n",
" cart[:] = i, x, y, dx, dy, k\n",
" \n",
" if len(carts) - len(crashed) == 1:\n",
" for i, x, y, *_ in carts:\n",
" if i not in crashed:\n",
" return f\"{x},{y}\"\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"180 ms ± 15.2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

177
Python/2018/14.ipynb Normal file
View file

@ -0,0 +1,177 @@
{
"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 = 2018, 14\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'1052903161'"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" r = [3, 7]\n",
" p = 0\n",
" q = 1\n",
" n = int(puzzle)\n",
" while len(r) < n + 10:\n",
" r += [*map(int, str(r[p] + r[q]))]\n",
" p = (p + r[p] + 1) % len(r)\n",
" q = (q + r[q] + 1) % len(r)\n",
" return \"\".join(map(str, r[n:n+10]))\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"414 ms ± 31.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"20165504"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def gen():\n",
" r = [3, 7]\n",
" p = 0\n",
" q = 1\n",
" yield from r\n",
" while True:\n",
" x = [*map(int, str(r[p] + r[q]))]\n",
" yield from x\n",
" r += x\n",
" p = (p + r[p] + 1) % len(r)\n",
" q = (q + r[q] + 1) % len(r)\n",
"\n",
"def solve2():\n",
" n = [*map(int, puzzle)]\n",
" g = gen()\n",
" lst = [i for _, i in zip(n, g)]\n",
" cnt = 0\n",
" for num in g:\n",
" if lst == n:\n",
" return cnt\n",
" lst.pop(0)\n",
" lst.append(num)\n",
" cnt += 1\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"26.1 s ± 955 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

340
Python/2018/15.ipynb Normal file
View file

@ -0,0 +1,340 @@
{
"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 = 2018, 15\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"237490"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def adj(x, y): return [(x,y-1),(x-1,y),(x+1,y),(x,y+1)]\n",
"\n",
"def solve1():\n",
" entities = {}\n",
" walls = set()\n",
" idx = 0\n",
" for i, line in enumerate(plines):\n",
" for j, c in enumerate(line):\n",
" if c == \"#\": walls.add((j, i))\n",
" elif c != \".\":\n",
" entities[(j, i)] = ((idx, c == \"E\", 200))\n",
" idx += 1\n",
" \n",
" rnd = 0\n",
" while True:\n",
" done = False\n",
" orig = entities.copy()\n",
" for x, y in sorted(entities, key=lambda a: a[::-1]):\n",
" if (x, y) not in entities: continue\n",
" idx, elf, hp = entities[(x, y)]\n",
" if idx != orig[(x, y)][0]: continue\n",
" \n",
" if not any(q[1] != elf for q in entities.values()):\n",
" done = True\n",
" break\n",
"\n",
" in_range = [(p, q) for p in adj(x, y) if (q := entities.get(p)) and q[1] != elf]\n",
" if not in_range:\n",
" queue = [(0, x, y)]\n",
" visited = set()\n",
" dist = None\n",
" nearest = []\n",
" while queue:\n",
" d, p, q = queue.pop(0)\n",
" \n",
" if (p, q) in visited: continue\n",
" visited.add((p, q))\n",
" \n",
" if any(e[1] != elf for r in adj(p, q) if (e := entities.get(r))):\n",
" if dist is None:\n",
" dist = d\n",
" elif d > dist: break\n",
" nearest.append((p, q))\n",
" \n",
" for r in adj(p, q):\n",
" if r in walls: continue\n",
" if (e := entities.get(r)) and e[1] == elf: continue\n",
" queue.append((d + 1, *r))\n",
" \n",
" if not nearest: continue\n",
" \n",
" target = min(nearest, key=lambda a: a[::-1]) \n",
" \n",
" queue = [(0, *target)]\n",
" visited = set()\n",
" dist = None\n",
" nearest = []\n",
" while queue:\n",
" d, p, q = queue.pop(0)\n",
" \n",
" if (p, q) in visited: continue\n",
" visited.add((p, q))\n",
" \n",
" if (x, y) in adj(p, q):\n",
" if dist is None:\n",
" dist = d\n",
" elif d > dist: break\n",
" nearest.append((p, q))\n",
" \n",
" for r in adj(p, q):\n",
" if r in walls: continue\n",
" if (e := entities.get(r)) and e[1] == elf: continue\n",
" queue.append((d + 1, *r))\n",
"\n",
" if not nearest: continue\n",
" \n",
" g = min(nearest, key=lambda a: a[::-1]) \n",
" \n",
" entities[g] = entities.pop((x, y))\n",
" x, y = g\n",
" \n",
" in_range = [(p, q) for p in adj(x, y) if (q := entities.get(p)) and q[1] != elf]\n",
" if in_range:\n",
" in_range.sort(key=lambda a: (a[1][2], a[0][::-1]))\n",
" p, (idx2, elf2, hp2) = in_range[0]\n",
" hp2 -= 3\n",
" if hp2 <= 0:\n",
" entities.pop(p)\n",
" else:\n",
" entities[p] = idx2, elf2, hp2\n",
" \n",
" if done: break\n",
" \n",
" rnd += 1\n",
"\n",
" return rnd * sum(e[2] for e in entities.values())\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1.33 s ± 164 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"38424"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def simulate(ap):\n",
" entities = {}\n",
" walls = set()\n",
" idx = 0\n",
" for i, line in enumerate(plines):\n",
" for j, c in enumerate(line):\n",
" if c == \"#\": walls.add((j, i))\n",
" elif c != \".\":\n",
" entities[(j, i)] = ((idx, c == \"E\", 200))\n",
" idx += 1\n",
" \n",
" rnd = 0\n",
" while True:\n",
" done = False\n",
" orig = entities.copy()\n",
" for x, y in sorted(entities, key=lambda a: a[::-1]):\n",
" if (x, y) not in entities: continue\n",
" idx, elf, hp = entities[(x, y)]\n",
" if idx != orig[(x, y)][0]: continue\n",
" \n",
" if not any(q[1] != elf for q in entities.values()):\n",
" done = True\n",
" break\n",
"\n",
" in_range = [(p, q) for p in adj(x, y) if (q := entities.get(p)) and q[1] != elf]\n",
" if not in_range:\n",
" queue = [(0, x, y)]\n",
" visited = set()\n",
" dist = None\n",
" nearest = []\n",
" while queue:\n",
" d, p, q = queue.pop(0)\n",
" \n",
" if (p, q) in visited: continue\n",
" visited.add((p, q))\n",
" \n",
" if any(e[1] != elf for r in adj(p, q) if (e := entities.get(r))):\n",
" if dist is None:\n",
" dist = d\n",
" elif d > dist: break\n",
" nearest.append((p, q))\n",
" \n",
" for r in adj(p, q):\n",
" if r in walls: continue\n",
" if (e := entities.get(r)) and e[1] == elf: continue\n",
" queue.append((d + 1, *r))\n",
" \n",
" if not nearest: continue\n",
" \n",
" target = min(nearest, key=lambda a: a[::-1]) \n",
" \n",
" queue = [(0, *target)]\n",
" visited = set()\n",
" dist = None\n",
" nearest = []\n",
" while queue:\n",
" d, p, q = queue.pop(0)\n",
" \n",
" if (p, q) in visited: continue\n",
" visited.add((p, q))\n",
" \n",
" if (x, y) in adj(p, q):\n",
" if dist is None:\n",
" dist = d\n",
" elif d > dist: break\n",
" nearest.append((p, q))\n",
" \n",
" for r in adj(p, q):\n",
" if r in walls: continue\n",
" if (e := entities.get(r)) and e[1] == elf: continue\n",
" queue.append((d + 1, *r))\n",
"\n",
" if not nearest: continue\n",
" \n",
" g = min(nearest, key=lambda a: a[::-1]) \n",
" \n",
" entities[g] = entities.pop((x, y))\n",
" x, y = g\n",
" \n",
" in_range = [(p, q) for p in adj(x, y) if (q := entities.get(p)) and q[1] != elf]\n",
" if in_range:\n",
" in_range.sort(key=lambda a: (a[1][2], a[0][::-1]))\n",
" p, (idx2, elf2, hp2) = in_range[0]\n",
" hp2 -= ap if elf else 3\n",
" if hp2 <= 0:\n",
" if elf2: return -1\n",
" entities.pop(p)\n",
" else:\n",
" entities[p] = idx2, elf2, hp2\n",
" \n",
" if done: break\n",
" \n",
" rnd += 1\n",
"\n",
" return rnd * sum(e[2] for e in entities.values())\n",
"\n",
"def solve2():\n",
" ap = 4\n",
" while (res := simulate(ap)) < 0: ap += 1\n",
" return res\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"6.33 s ± 358 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

208
Python/2018/16.ipynb Normal file
View file

@ -0,0 +1,208 @@
{
"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 = 2018, 16\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"651"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"opcodes = [\n",
" lambda reg, a, b: reg[a] + reg[b], # addr\n",
" lambda reg, a, b: reg[a] + b, # addi\n",
" lambda reg, a, b: reg[a] * reg[b], # mulr\n",
" lambda reg, a, b: reg[a] * b, # muli\n",
" lambda reg, a, b: reg[a] & reg[b], # banr\n",
" lambda reg, a, b: reg[a] & b, # bani\n",
" lambda reg, a, b: reg[a] | reg[b], # borr\n",
" lambda reg, a, b: reg[a] | b, # bori\n",
" lambda reg, a, b: reg[a], # setr\n",
" lambda reg, a, b: a, # seti\n",
" lambda reg, a, b: a > reg[b], # gtir\n",
" lambda reg, a, b: reg[a] > b, # gtri\n",
" lambda reg, a, b: reg[a] > reg[b], # gtrr\n",
" lambda reg, a, b: a == reg[b], # eqir\n",
" lambda reg, a, b: reg[a] == b, # eqri\n",
" lambda reg, a, b: reg[a] == reg[b], # eqrr\n",
"]\n",
"\n",
"def exec_opcode(reg, op, a, b, c):\n",
" reg[c] = int(op(reg, a, b))\n",
" \n",
"def test_opcode(before, after, op, a, b, c):\n",
" before = [*before]\n",
" exec_opcode(before, op, a, b, c)\n",
" return before == after\n",
"\n",
"def solve1():\n",
" out = 0\n",
" for before, instruction, after in map(str.splitlines, puzzle.split(\"\\n\\n\\n\")[0].split(\"\\n\\n\")):\n",
" before = eval(before.split(\": \")[1])\n",
" _, a, b, c = map(int, instruction.split())\n",
" after = eval(after.split(\": \")[1])\n",
" out += sum(test_opcode(before, after, op, a, b, c) for op in opcodes) >= 3\n",
" return out\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"33.4 ms ± 2.03 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"706"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve2():\n",
" codes = [opcodes.copy() for _ in range(16)]\n",
" m = [None] * 16\n",
" for before, instruction, after in map(str.splitlines, puzzle.split(\"\\n\\n\\n\")[0].split(\"\\n\\n\")):\n",
" before = eval(before.split(\": \")[1])\n",
" op, a, b, c = map(int, instruction.split())\n",
" after = eval(after.split(\": \")[1])\n",
" \n",
" for o in [*codes[op]]:\n",
" if not test_opcode(before, after, o, a, b, c):\n",
" codes[op].remove(o)\n",
" if len(codes[op]) == 1:\n",
" m[op] = codes[op][0]\n",
" \n",
" q = [x for x in m if x]\n",
" while q:\n",
" x = q.pop()\n",
" for i, lst in enumerate(codes):\n",
" if x in lst:\n",
" lst.remove(x)\n",
" if len(lst) == 1:\n",
" m[i] = lst[0]\n",
" q.append(m[i])\n",
"\n",
" reg = [0] * 4\n",
" for line in puzzle.split(\"\\n\\n\\n\\n\")[1].splitlines():\n",
" op, a, b, c = map(int, line.split())\n",
" exec_opcode(reg, m[op], a, b, c)\n",
" return reg[0]\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"31.7 ms ± 7.67 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

260
Python/2018/17.ipynb Normal file
View file

@ -0,0 +1,260 @@
{
"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 = 2018, 17\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"37858"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" clay = set()\n",
" miny = 1e1337\n",
" maxy = 0\n",
" for line in plines:\n",
" a, b = line.split(\", \")\n",
" a = int(a.split(\"=\")[1])\n",
" b1, b2 = map(int, b.split(\"=\")[1].split(\"..\"))\n",
" for i in range(b1, b2+1):\n",
" if line[0] == \"x\": x, y = a, i\n",
" else: x, y = i, a\n",
" clay.add((x, y))\n",
" miny = min(y, miny)\n",
" maxy = max(y, maxy)\n",
" \n",
" reachable = set()\n",
" water = set()\n",
" dp = {}\n",
" def flow(x, y):\n",
" if y > maxy: return False\n",
" if (x, y) in clay: return True\n",
" if (x, y) in dp:\n",
" return dp[(x, y)]\n",
" \n",
" reachable.add((x, y))\n",
" \n",
" if not flow(x, y + 1):\n",
" dp[(x, y)] = False\n",
" return False\n",
"\n",
" add = set()\n",
" ok = True\n",
" \n",
" k = x\n",
" while (k, y) not in clay:\n",
" add.add((k, y))\n",
" if not flow(k, y + 1):\n",
" ok = False\n",
" break\n",
" k -= 1\n",
" \n",
" k = x\n",
" while (k, y) not in clay:\n",
" add.add((k, y))\n",
" if not flow(k, y + 1):\n",
" ok = False\n",
" break\n",
" k += 1\n",
" \n",
" reachable.update(add)\n",
" if ok: water.update(add)\n",
" \n",
" dp[(x, y)] = ok\n",
" return ok\n",
" \n",
" flow(500, 0)\n",
" \n",
" return sum((x, y) != (500, 0) and y in range(miny, maxy+1) for x, y in reachable)\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1.83 s ± 283 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"30410"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve2():\n",
" clay = set()\n",
" miny = 1e1337\n",
" maxy = 0\n",
" for line in plines:\n",
" a, b = line.split(\", \")\n",
" a = int(a.split(\"=\")[1])\n",
" b1, b2 = map(int, b.split(\"=\")[1].split(\"..\"))\n",
" for i in range(b1, b2+1):\n",
" if line[0] == \"x\": x, y = a, i\n",
" else: x, y = i, a\n",
" clay.add((x, y))\n",
" miny = min(y, miny)\n",
" maxy = max(y, maxy)\n",
" \n",
" reachable = set()\n",
" water = set()\n",
" dp = {}\n",
" def flow(x, y):\n",
" if y > maxy: return False\n",
" if (x, y) in clay: return True\n",
" if (x, y) in dp:\n",
" return dp[(x, y)]\n",
" \n",
" reachable.add((x, y))\n",
" \n",
" if not flow(x, y + 1):\n",
" dp[(x, y)] = False\n",
" return False\n",
"\n",
" add = set()\n",
" ok = True\n",
" \n",
" k = x\n",
" while (k, y) not in clay:\n",
" add.add((k, y))\n",
" if not flow(k, y + 1):\n",
" ok = False\n",
" break\n",
" k -= 1\n",
" \n",
" k = x\n",
" while (k, y) not in clay:\n",
" add.add((k, y))\n",
" if not flow(k, y + 1):\n",
" ok = False\n",
" break\n",
" k += 1\n",
" \n",
" reachable.update(add)\n",
" if ok: water.update(add)\n",
" \n",
" dp[(x, y)] = ok\n",
" return ok\n",
" \n",
" flow(500, 0)\n",
" \n",
" return len(water)\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1.71 s ± 239 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

193
Python/2018/18.ipynb Normal file
View file

@ -0,0 +1,193 @@
{
"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 = 2018, 18\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"594712"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def cntAdj(grid, y, x, t):\n",
" return sum(grid[i][j] == t for i in range(y-1, y+2) for j in range(x-1, x+2) if (i, j) != (y, x) and i in range(len(grid)) and j in range(len(grid[i])))\n",
"\n",
"def solve1():\n",
" grid = plines\n",
" for _ in range(10):\n",
" new_grid = []\n",
" for i, line in enumerate(grid):\n",
" new_line = \"\"\n",
" for j, c in enumerate(line):\n",
" if c == \".\" and cntAdj(grid, i, j, \"|\") >= 3: new_line += \"|\"\n",
" elif c == \"|\" and cntAdj(grid, i, j, \"#\") >= 3: new_line += \"#\"\n",
" elif c == \"#\" and not (cntAdj(grid, i, j, \"#\") >= 1 and cntAdj(grid, i, j, \"|\") >= 1): new_line += \".\"\n",
" else: new_line += c\n",
" new_grid.append(new_line)\n",
" grid = new_grid\n",
" \n",
" a = sum(line.count(\"|\") for line in grid)\n",
" b = sum(line.count(\"#\") for line in grid)\n",
" return a * b\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"294 ms ± 69.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"203138"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def next_iteration(grid):\n",
" new_grid = []\n",
" for i, line in enumerate(grid):\n",
" new_line = \"\"\n",
" for j, c in enumerate(line):\n",
" if c == \".\" and cntAdj(grid, i, j, \"|\") >= 3: new_line += \"|\"\n",
" elif c == \"|\" and cntAdj(grid, i, j, \"#\") >= 3: new_line += \"#\"\n",
" elif c == \"#\" and not (cntAdj(grid, i, j, \"#\") >= 1 and cntAdj(grid, i, j, \"|\") >= 1): new_line += \".\"\n",
" else: new_line += c\n",
" new_grid.append(new_line)\n",
" return new_grid\n",
"\n",
"def solve2():\n",
" grid = plines\n",
" seen = {}\n",
" i = 0\n",
" while tuple(grid) not in seen:\n",
" seen[tuple(grid)] = i\n",
" grid = next_iteration(grid)\n",
" i += 1\n",
" \n",
" cycle = i - seen[tuple(grid)]\n",
" \n",
" for _ in range((1000000000 - i) % cycle):\n",
" grid = next_iteration(grid)\n",
" \n",
" a = sum(line.count(\"|\") for line in grid)\n",
" b = sum(line.count(\"#\") for line in grid)\n",
" return a * b\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"13.1 s ± 634 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

242
Python/2018/19.ipynb Normal file
View file

@ -0,0 +1,242 @@
{
"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 = 2018, 19\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"opcodes = {\n",
" \"addr\": lambda reg, a, b: reg[a] + reg[b], # addr\n",
" \"addi\": lambda reg, a, b: reg[a] + b, # addi\n",
" \"mulr\": lambda reg, a, b: reg[a] * reg[b], # mulr\n",
" \"muli\": lambda reg, a, b: reg[a] * b, # muli\n",
" \"banr\": lambda reg, a, b: reg[a] & reg[b], # banr\n",
" \"bani\": lambda reg, a, b: reg[a] & b, # bani\n",
" \"borr\": lambda reg, a, b: reg[a] | reg[b], # borr\n",
" \"bori\": lambda reg, a, b: reg[a] | b, # bori\n",
" \"setr\": lambda reg, a, b: reg[a], # setr\n",
" \"seti\": lambda reg, a, b: a, # seti\n",
" \"gtir\": lambda reg, a, b: a > reg[b], # gtir\n",
" \"gtri\": lambda reg, a, b: reg[a] > b, # gtri\n",
" \"gtrr\": lambda reg, a, b: reg[a] > reg[b], # gtrr\n",
" \"eqir\": lambda reg, a, b: a == reg[b], # eqir\n",
" \"eqri\": lambda reg, a, b: reg[a] == b, # eqri\n",
" \"eqrr\": lambda reg, a, b: reg[a] == reg[b], # eqrr\n",
"}\n",
"\n",
"def exec_opcode(reg, op, a, b, c):\n",
" reg[c] = int(opcodes[op](reg, a, b))"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1568"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" ip, *instructions = plines\n",
" ip = int(ip.split()[1])\n",
" reg = [0] * 6\n",
" while reg[ip] in range(len(instructions)):\n",
" op, a, b, c = instructions[reg[ip]].split()\n",
" exec_opcode(reg, op, *map(int, [a,b,c]))\n",
" reg[ip] += 1\n",
" return reg[0]\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"13.5 s ± 619 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"000| ip += 16\n",
"001| r5 = 1\n",
"002| r3 = 1\n",
"003| r4 = r5 * r3\n",
"004| r4 = r4 == r1\n",
"005| ip += r4\n",
"006| ip += 1\n",
"007| r0 += r5\n",
"008| r3 += 1\n",
"009| r4 = r3 > r1\n",
"010| ip += r4\n",
"011| ip = 2\n",
"012| r5 += 1\n",
"013| r4 = r5 > r1\n",
"014| ip += r4\n",
"015| ip = 1\n",
"016| ip *= ip\n",
"017| r1 += 2\n",
"018| r1 *= r1\n",
"019| r1 *= ip\n",
"020| r1 *= 11\n",
"021| r4 += 2\n",
"022| r4 *= ip\n",
"023| r4 += 12\n",
"024| r1 += r4\n",
"025| ip += r0\n",
"026| ip = 0\n",
"027| r4 = ip\n",
"028| r4 *= ip\n",
"029| r4 += ip\n",
"030| r4 *= ip\n",
"031| r4 *= 14\n",
"032| r4 *= ip\n",
"033| r1 += r4\n",
"034| r0 = 0\n",
"035| ip = 0\n"
]
}
],
"source": [
"ip, *instructions = plines\n",
"ip = int(ip.split()[1])\n",
"\n",
"reg = lambda i: \"ip\" if i == ip else f\"r{i}\"\n",
"\n",
"for i, (op, a, b, c) in enumerate(map(str.split, instructions)):\n",
" a, b, c = map(int, [a, b, c])\n",
" if op[:2] in [\"eq\", \"gt\"]:\n",
" print(f\"{i:03}| {reg(c)} = {reg(a) if op[2]=='r' else a} { {'eq':'==','gt':'>'}[op[:2]]} {reg(b) if op[3]=='r' else b}\")\n",
" elif op[:3] == \"set\":\n",
" print(f\"{i:03}| {reg(c)} = {reg(a) if op[-1]=='r' else a}\")\n",
" else:\n",
" if a == c:\n",
" print(f\"{i:03}| {reg(c)} { {'add':'+','mul':'*','ban':'&','bor':'|'}[op[:3]]}= {reg(b) if op[-1]=='r' else b}\") \n",
" elif b == c and op[-1] == \"r\":\n",
" print(f\"{i:03}| {reg(c)} { {'add':'+','mul':'*','ban':'&','bor':'|'}[op[:3]]}= {reg(a)}\") \n",
" else:\n",
" print(f\"{i:03}| {reg(c)} = {reg(a)} { {'add':'+','mul':'*','ban':'&','bor':'|'}[op[:3]]} {reg(b) if op[-1]=='r' else b}\") \n",
" "
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"19030032"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"r1 = 2 * 2 * 19 * 11 + 2 * 22 + 12 + (27 * 28 + 29) * 30 * 14 * 32\n",
"r0 = 0\n",
"\n",
"for r5 in range(1, r1 + 1):\n",
" if r1 % r5 == 0: r0 += r5\n",
"# for r3 in range(1, r1 + 1):\n",
"# if r3 == r1 / r5: r0 += r5\n",
"\n",
"r0"
]
}
],
"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
}

239
Python/2018/20.ipynb Normal file
View file

@ -0,0 +1,239 @@
{
"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 = 2018, 20\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3545"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def parse_regex(regex):\n",
" regex = regex.strip(\"^$\")\n",
" stack = [[]]\n",
" \n",
" for c in regex:\n",
" if c == \"(\":\n",
" stack.append([])\n",
" stack.append([])\n",
" elif c == \")\":\n",
" x = stack.pop()\n",
" y = stack.pop()\n",
" y.append(x)\n",
" stack[-1].append(tuple(y))\n",
" elif c == \"|\":\n",
" x = stack.pop()\n",
" stack[-1].append(x)\n",
" stack.append([])\n",
" else:\n",
" stack[-1].append(c)\n",
" \n",
" return stack[0]\n",
"\n",
"dp = set()\n",
"\n",
"def traverse(graph, regex, x, y, decisions=None, pop_after=None):\n",
" decisions = decisions or ()\n",
" if (x, y, decisions) in dp: return\n",
" dp.add((x, y, decisions))\n",
" \n",
" i = 0\n",
" while i < len(regex):\n",
" if i == pop_after: decisions = (*decisions[:-1], None)\n",
" \n",
" elem = regex[i]\n",
" prev = x, y\n",
" if isinstance(elem, tuple):\n",
" for j, option in enumerate(elem):\n",
" traverse(graph, option + regex[i+1:], x, y, (*decisions, j), len(option))\n",
" break\n",
" elif elem == \"N\":\n",
" y -= 1\n",
" elif elem == \"E\":\n",
" x += 1\n",
" elif elem == \"S\":\n",
" y += 1\n",
" elif elem == \"W\":\n",
" x -= 1\n",
" \n",
" graph.setdefault(prev, set()).add((x, y))\n",
" graph.setdefault((x, y), set()).add(prev)\n",
" \n",
" i += 1\n",
"\n",
"def solve1():\n",
" dp.clear()\n",
" regex = parse_regex(puzzle)\n",
" graph = {}\n",
" traverse(graph, regex, 0, 0)\n",
" \n",
" queue = [(0, 0, 0)]\n",
" visited = set()\n",
" out = 0\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",
" out = max(out, d)\n",
" \n",
" for p, q in graph.get((x, y), []):\n",
" if (p, q) not in visited: queue.append((d+1, p, q))\n",
" \n",
" return out\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"67.1 ms ± 12.6 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"7838"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve2():\n",
" dp.clear()\n",
" regex = parse_regex(puzzle)\n",
" graph = {}\n",
" traverse(graph, regex, 0, 0)\n",
" \n",
" queue = [(0, 0, 0)]\n",
" visited = set()\n",
" out = 0\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 d >= 1000: out += 1\n",
" \n",
" for p, q in graph.get((x, y), []):\n",
" if (p, q) not in visited: queue.append((d+1, p, q))\n",
" \n",
" return out\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"65 ms ± 14.4 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

263
Python/2018/21.ipynb Normal file
View file

@ -0,0 +1,263 @@
{
"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 = 2018, 21\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"000| r1 = 123\n",
"001| r1 &= 456\n",
"002| r1 = r1 == 72\n",
"003| ip += r1\n",
"004| ip = 0\n",
"005| r1 = 0\n",
"006| r5 = r1 | 65536\n",
"007| r1 = 8586263\n",
"008| r2 = r5 & 255\n",
"009| r1 += r2\n",
"010| r1 &= 16777215\n",
"011| r1 *= 65899\n",
"012| r1 &= 16777215\n",
"013| r2 = 256 > r5\n",
"014| ip += r2\n",
"015| ip += 1\n",
"016| ip = 27\n",
"017| r2 = 0\n",
"018| r3 = r2 + 1\n",
"019| r3 *= 256\n",
"020| r3 = r3 > r5\n",
"021| ip += r3\n",
"022| ip += 1\n",
"023| ip = 25\n",
"024| r2 += 1\n",
"025| ip = 17\n",
"026| r5 = r2\n",
"027| ip = 7\n",
"028| r2 = r1 == r0\n",
"029| ip += r2\n",
"030| ip = 5\n"
]
}
],
"source": [
"ip, *instructions = plines\n",
"ip = int(ip.split()[1])\n",
"\n",
"reg = lambda i: \"ip\" if i == ip else f\"r{i}\"\n",
"\n",
"for i, (op, a, b, c) in enumerate(map(str.split, instructions)):\n",
" a, b, c = map(int, [a, b, c])\n",
" if op[:2] in [\"eq\", \"gt\"]:\n",
" print(f\"{i:03}| {reg(c)} = {reg(a) if op[2]=='r' else a} { {'eq':'==','gt':'>'}[op[:2]]} {reg(b) if op[3]=='r' else b}\")\n",
" elif op[:3] == \"set\":\n",
" print(f\"{i:03}| {reg(c)} = {reg(a) if op[-1]=='r' else a}\")\n",
" else:\n",
" if a == c:\n",
" print(f\"{i:03}| {reg(c)} { {'add':'+','mul':'*','ban':'&','bor':'|'}[op[:3]]}= {reg(b) if op[-1]=='r' else b}\") \n",
" elif b == c and op[-1] == \"r\":\n",
" print(f\"{i:03}| {reg(c)} { {'add':'+','mul':'*','ban':'&','bor':'|'}[op[:3]]}= {reg(a)}\") \n",
" else:\n",
" print(f\"{i:03}| {reg(c)} = {reg(a)} { {'add':'+','mul':'*','ban':'&','bor':'|'}[op[:3]]} {reg(b) if op[-1]=='r' else b}\") "
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"assert 123 & 456 == 72\n",
"\n",
"r1 = 0\n",
"\n",
"while True:\n",
" r5 = r1 | 65536\n",
" r1 = 8586263\n",
"\n",
" while r5:\n",
" r1 += r5 & 255\n",
" r1 &= 16777215\n",
" r1 *= 65899\n",
" r1 &= 16777215\n",
" \n",
" r5 //= 256\n",
"\n",
" if r1 == r0: break"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"5970144"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" r1 = 0\n",
" r5 = r1 | 65536\n",
" r1 = 8586263\n",
"\n",
" while r5:\n",
" r1 += r5 & 255\n",
" r1 &= 16777215\n",
" r1 *= 65899\n",
" r1 &= 16777215\n",
"\n",
" r5 //= 256\n",
" return r1\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1.08 µs ± 60.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"13943296"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve2():\n",
" r1 = 0\n",
" seen = set()\n",
" out = r1\n",
" while r1 not in seen:\n",
" out = r1\n",
" seen.add(r1)\n",
" r5 = r1 | 65536\n",
" r1 = 8586263\n",
"\n",
" while r5:\n",
" r1 += r5 & 255\n",
" r1 &= 16777215\n",
" r1 *= 65899\n",
" r1 &= 16777215\n",
"\n",
" r5 //= 256\n",
"\n",
" return out\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"13.4 ms ± 877 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

183
Python/2018/22.ipynb Normal file
View file

@ -0,0 +1,183 @@
{
"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 = 2018, 22\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"7743"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"depth = int(plines[0].split()[1])\n",
"tx, ty = map(int, plines[1].split()[1].split(\",\"))\n",
"\n",
"dp = {}\n",
"def get_geologic_index(x, y):\n",
" if (x, y) == (tx, ty): return 0\n",
" if y == 0: return x * 16807\n",
" if x == 0: return y * 48271\n",
" if (x, y) not in dp: dp[(x, y)] = get_erosion_level(x-1, y) * get_erosion_level(x, y-1)\n",
" return dp[(x, y)]\n",
"\n",
"def get_erosion_level(x, y):\n",
" return (get_geologic_index(x, y) + depth) % 20183\n",
"\n",
"def solve1():\n",
" return sum(get_erosion_level(x, y) % 3 for y in range(ty+1) for x in range(tx+1))\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"6.58 ms ± 456 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1029"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import heapq\n",
"\n",
"def solve2():\n",
" queue = [(0, 0, 0, 1)]\n",
" visited = set()\n",
" while queue:\n",
" d, x, y, e = heapq.heappop(queue)\n",
" \n",
" if (x, y, e) in visited: continue\n",
" visited.add((x, y, e))\n",
" \n",
" if (x, y, e) == (tx, ty, 1):\n",
" return d\n",
" \n",
" t = get_erosion_level(x, y) % 3\n",
" \n",
" heapq.heappush(queue, (d + 7, x, y, (-e-t)%3))\n",
" \n",
" for p, q in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]:\n",
" if p < 0 or q < 0: continue\n",
" t = get_erosion_level(p, q) % 3\n",
" if t == e: continue\n",
" heapq.heappush(queue, (d + 1, p, q, e))\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"18.4 s ± 659 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

185
Python/2018/23.ipynb Normal file
View file

@ -0,0 +1,185 @@
{
"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 = 2018, 23\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"730"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" bots = []\n",
" for pos, r in map(str.split, plines):\n",
" x, y, z = map(int, pos.split(\"<\")[1].strip(\">,\").split(\",\"))\n",
" r = int(r.split(\"=\")[1])\n",
" bots.append((x, y, z, r))\n",
" \n",
" sx, sy, sz, sr = max(bots, key=lambda a: a[3])\n",
" return sum(abs(x-sx)+abs(y-sy)+abs(z-sz) <= sr for x, y, z, _ in bots)\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2.38 ms ± 225 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"48202279"
],
"text/plain": [
"48202279"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from z3 import *\n",
"\n",
"def solve2():\n",
" bots = []\n",
" for pos, r in map(str.split, plines):\n",
" x, y, z = map(int, pos.split(\"<\")[1].strip(\">,\").split(\",\"))\n",
" r = int(r.split(\"=\")[1])\n",
" bots.append((x, y, z, r))\n",
"\n",
" zabs = lambda x: If(x >= 0, x, -x)\n",
"\n",
" x, y, z = Ints(\"x y z\")\n",
" in_ranges = [Int(f\"in_range_{i}\") for i in range(len(bots))]\n",
" range_count = Int(\"sum\")\n",
" \n",
" o = Optimize()\n",
" for (nx, ny, nz, nr), ir in zip(bots, in_ranges):\n",
" o.add(ir == If(zabs(x - nx) + zabs(y - ny) + zabs(z - nz) <= nr, 1, 0))\n",
"\n",
" o.add(range_count == sum(in_ranges))\n",
" \n",
" dist_from_zero = Int(\"dist\")\n",
" o.add(dist_from_zero == zabs(x) + zabs(y) + zabs(z))\n",
" \n",
" h1 = o.maximize(range_count)\n",
" h2 = o.minimize(dist_from_zero)\n",
"\n",
" o.check()\n",
" return o.lower(h2)\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1min 31s ± 15.4 s per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

253
Python/2018/24.ipynb Normal file
View file

@ -0,0 +1,253 @@
{
"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 = 2018, 24\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"from dataclasses import dataclass\n",
"import re\n",
"\n",
"@dataclass\n",
"class Group:\n",
" army: int\n",
" units: int\n",
" hp: int\n",
" ap: int\n",
" at: str\n",
" init: int\n",
" weak: set[str]\n",
" immune: set[str]\n",
" \n",
" def __hash__(self): return id(self)\n",
" \n",
" @staticmethod\n",
" def parse(army, line, boost=0):\n",
" units, hp, _, extra, ap, at, init = re.match(r\"^(\\d+) units each with (\\d+) hit points( \\((.*)\\))? with an attack that does (\\d+) (\\w+) damage at initiative (\\d+)$\", line).groups()\n",
" \n",
" weak = set()\n",
" immune = set()\n",
" for part in extra.split(\"; \") if extra else []:\n",
" t, _, *xs = part.split()\n",
" {\"weak\": weak, \"immune\": immune}[t].update(x.strip(\",\") for x in xs)\n",
" \n",
" return Group(army, int(units), int(hp), int(ap) + boost, at, int(init), weak, immune)\n",
" \n",
" @property\n",
" def ep(self):\n",
" return self.units * self.ap\n",
" \n",
" @property\n",
" def dead(self):\n",
" return self.units <= 0\n",
" \n",
" def calc_damage(self, target):\n",
" if self.at in target.immune: return 0\n",
" mul = 2 if self.at in target.weak else 1\n",
" return self.ep * mul\n",
" \n",
" def attack(self, target):\n",
" damage = self.calc_damage(target) // target.hp\n",
" target.units -= damage\n",
" return damage"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"22996"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def solve1():\n",
" immune, infect = [[Group.parse(i, group) for group in army.splitlines()[1:]] for i, army in enumerate(puzzle.split(\"\\n\\n\"))]\n",
" \n",
" while immune and infect:\n",
" targets = {}\n",
" imm_att = set(immune)\n",
" inf_att = set(infect)\n",
" \n",
" for group in sorted(immune + infect, key=lambda g: (-g.ep, -g.init)):\n",
" attackable = [inf_att, imm_att][group.army]\n",
" if not attackable: continue\n",
" target = max(attackable, key=lambda g: (group.calc_damage(g), g.ep, g.init))\n",
" if not group.calc_damage(target): continue\n",
" attackable.remove(target)\n",
" targets[group] = target\n",
" \n",
" for group, target in sorted(targets.items(), key=lambda a: -a[0].init):\n",
" if group.dead: continue\n",
" group.attack(target)\n",
" \n",
" immune, infect = [[g for g in x if not g.dead] for x in [immune, infect]]\n",
" \n",
" return sum(g.units for g in immune + infect)\n",
"\n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"49.2 ms ± 15.7 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"4327"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def test(boost):\n",
" immune, infect = [[Group.parse(i, group, boost if i == 0 else 0) for group in army.splitlines()[1:]] for i, army in enumerate(puzzle.split(\"\\n\\n\"))]\n",
" \n",
" while immune and infect:\n",
" targets = {}\n",
" imm_att = set(immune)\n",
" inf_att = set(infect)\n",
" \n",
" for group in sorted(immune + infect, key=lambda g: (-g.ep, -g.init)):\n",
" attackable = [inf_att, imm_att][group.army]\n",
" if not attackable: continue\n",
" target = max(attackable, key=lambda g: (group.calc_damage(g), g.ep, g.init))\n",
" if not group.calc_damage(target): continue\n",
" attackable.remove(target)\n",
" targets[group] = target\n",
" \n",
" ok = False\n",
" for group, target in sorted(targets.items(), key=lambda a: -a[0].init):\n",
" if group.dead: continue\n",
" if group.attack(target): ok = True\n",
" \n",
" if not ok:\n",
" break\n",
" \n",
" immune, infect = [[g for g in x if not g.dead] for x in [immune, infect]]\n",
" \n",
" if infect: return None\n",
" return sum(g.units for g in immune)\n",
"\n",
"def solve2():\n",
" boost = 0\n",
" while not (out := test(boost)): boost += 1\n",
" return out\n",
"\n",
"solve2()"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3.63 s ± 289 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve2()"
]
}
],
"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
}

121
Python/2018/25.ipynb Normal file
View file

@ -0,0 +1,121 @@
{
"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 = 2018, 25\n",
"\n",
"puzzle = aoc.setup(year, day)\n",
"plines = puzzle.splitlines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"394"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"class UnionFind:\n",
" def __init__(self, n):\n",
" self.parents = list(range(n))\n",
" \n",
" def find(self, x):\n",
" if self.parents[x] == x: return x\n",
" self.parents[x] = self.find(self.parents[x])\n",
" return self.parents[x]\n",
" \n",
" def merge(self, x, y):\n",
" x = self.find(x)\n",
" y = self.find(y)\n",
" self.parents[x] = y\n",
"\n",
"def solve1():\n",
" coords = [tuple(map(int, line.split(\",\"))) for line in plines]\n",
" uf = UnionFind(len(coords))\n",
" for i in range(len(coords)):\n",
" for j in range(i+1, len(coords)):\n",
" if sum(abs(a-b) for a, b in zip(coords[i], coords[j])) <= 3:\n",
" uf.merge(i, j)\n",
" return len(set(map(uf.find, range(len(coords)))))\n",
" \n",
"solve1()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1.37 s ± 129 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
}
],
"source": [
"%timeit solve1()"
]
}
],
"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
}

View file

@ -0,0 +1,4 @@
out = 0
for line in open("input.txt").read().splitlines():
out += int(line)
print(out)

View file

@ -0,0 +1,11 @@
lines = open("input.txt").read().splitlines()
freq = 0
seen = {0}
while True:
for line in lines:
freq += int(line)
if freq in seen:
print(freq)
exit()
else:
seen.add(freq)

View file

@ -0,0 +1,9 @@
def count(box, n):
return any(box.count(c) == n for c in set(box))
counter = {2: 0, 3: 0}
for line in open("input.txt").read().splitlines():
counter[2] += count(line, 2)
counter[3] += count(line, 3)
print(counter[2] * counter[3])

View file

@ -0,0 +1,9 @@
def compare(a, b):
return len(a) == len(b) and sum(x != y for x, y in zip(a, b)) == 1
lines = open("input.txt").read().splitlines()
for a in lines:
for b in lines:
if compare(a, b):
print("".join(x for x, y in zip(a, b) if x == y))
exit()

View file

@ -0,0 +1,9 @@
import re
G = [[0 for _ in range(1000)] for _ in range(1000)]
for line in open("input.txt").read().splitlines():
offx, offy, wid, hei = map(int, re.match("^#\d+ @ (\d+),(\d+): (\d+)x(\d+)$", line).groups())
for x in range(wid):
for y in range(hei):
G[offx + x][offy + y] += 1
print(sum(x>=2 for row in G for x in row))

View file

@ -0,0 +1,14 @@
import re
claims = open("input.txt").read().splitlines()
G = [[0 for _ in range(1000)] for _ in range(1000)]
for line in claims:
offx, offy, wid, hei = map(int, re.match("^#\d+ @ (\d+),(\d+): (\d+)x(\d+)$", line).groups())
for x in range(wid):
for y in range(hei):
G[offx + x][offy + y] += 1
for line in claims:
id, offx, offy, wid, hei = map(int, re.match("^#(\d+) @ (\d+),(\d+): (\d+)x(\d+)$", line).groups())
if all(G[offx + x][offy + y] == 1 for x in range(wid) for y in range(hei)):
print(id)

View file

@ -0,0 +1,37 @@
from datetime import date, timedelta
import re
days = {}
for line in open("input.txt").read().splitlines():
day, hour, minute, action = re.match("^\[(\d\d\d\d-\d\d-\d\d) (\d\d):(\d\d)\] (.*)$", line).groups()
day = date.fromisoformat(day)
hour, minute = int(hour), int(minute)
match = re.match("^Guard #(\d+) begins shift$", action)
if match:
guard = int(match.group(1))
if hour == 23:
day += timedelta(days=1)
days.setdefault(day, [None, [None for _ in range(60)]])[0] = guard
elif action == "wakes up":
assert hour == 0
assert 0 <= minute < 60
days.setdefault(day, [None, [None for _ in range(60)]])[1][minute] = True
elif action == "falls asleep":
assert hour == 0
assert 0 <= minute < 60
days.setdefault(day, [None, [None for _ in range(60)]])[1][minute] = False
else:
assert False
guards = {}
for day, (guard, logs) in days.items():
awake = True
for i in range(60):
if logs[i] is None:
logs[i] = awake
else:
awake = logs[i]
if not awake:
guards.setdefault(guard, [0, {}])[0] += 1
guards[guard][1][i] = guards[guard][1].get(i, 0) + 1
guard = max(guards, key=lambda g: guards[g][0])
print(guard * max(guards[guard][1], key=lambda d: guards[guard][1][d]))

View file

@ -0,0 +1,43 @@
from datetime import date, timedelta
import re
days = {}
for line in open("input.txt").read().splitlines():
day, hour, minute, action = re.match("^\[(\d\d\d\d-\d\d-\d\d) (\d\d):(\d\d)\] (.*)$", line).groups()
day = date.fromisoformat(day)
hour, minute = int(hour), int(minute)
match = re.match("^Guard #(\d+) begins shift$", action)
if match:
guard = int(match.group(1))
if hour == 23:
day += timedelta(days=1)
days.setdefault(day, [None, [None for _ in range(60)]])[0] = guard
elif action == "wakes up":
assert hour == 0
assert 0 <= minute < 60
days.setdefault(day, [None, [None for _ in range(60)]])[1][minute] = True
elif action == "falls asleep":
assert hour == 0
assert 0 <= minute < 60
days.setdefault(day, [None, [None for _ in range(60)]])[1][minute] = False
else:
assert False
guards = {}
for day, (guard, logs) in days.items():
awake = True
for i in range(60):
if logs[i] is None:
logs[i] = awake
else:
awake = logs[i]
if not awake:
guards.setdefault(guard, [0, {}])[0] += 1
guards[guard][1][i] = guards[guard][1].get(i, 0) + 1
best_cnt = -1
out = None
for g in guards:
cnt, best_minute = max((guards[g][1].get(i, 0), i) for i in range(60))
if cnt > best_cnt:
best_cnt = cnt
out = best_minute * g
print(out)

View file

@ -0,0 +1,7 @@
stack = []
for c in open("input.txt").read().strip():
if stack and stack[-1].lower() == c.lower() and stack[-1].islower() != c.islower():
stack.pop()
else:
stack.append(c)
print(len(stack))

View file

@ -0,0 +1,13 @@
def react(poly, wo):
stack = []
for c in poly:
if c.lower() == wo.lower():
continue
if stack and stack[-1].lower() == c.lower() and stack[-1].islower() != c.islower():
stack.pop()
else:
stack.append(c)
return len(stack)
inp = open("input.txt").read().strip()
print(min(react(inp, c) for c in set(inp.lower())))

Some files were not shown because too many files have changed in this diff Show more