Added 2021 (python)

This commit is contained in:
Karma Riuk
2023-08-02 11:46:44 +02:00
parent 410815acf8
commit 11600f7ba9
82 changed files with 8693 additions and 0 deletions

10
2021/11/input Normal file
View File

@ -0,0 +1,10 @@
6318185732
1122687135
5173237676
8754362612
5718474666
8443654137
1247634346
1446514585
6717288267
1727871228

59
2021/11/prog.py Normal file
View File

@ -0,0 +1,59 @@
VERBOSE = True
def verbose(s = "", *args, **kwargs):
if VERBOSE:
print(s, *args, **kwargs)
def get_input(sample = False, part = 1):
with open(f'sample_p{part}' if sample else 'input', 'r') as f:
return [[int(i) for i in line.strip()] for line in f.readlines()]
def result(inp, part = 1, steps = 100, grid = False):
res = 0;
for step in range(1, steps+1 if part == 1 else 2**31 - 1):
# increment each octopus
inp = [[i+1 for i in line] for line in inp]
# get the ones about to flash
queue = []
idx = 0
for y, row in enumerate(inp):
for x, cell in enumerate(row):
if cell > 9:
queue.append((x, y))
while idx < len(queue):
res += 1
x, y = queue[idx]
idx += 1
inp[y][x] = 0
for d in [(x-1, y-1), (x, y-1), (x+1, y-1),
(x-1, y), (x+1, y),
(x-1, y+1), (x, y+1), (x+1, y+1)]:
x1, y1 = d
if x1 < 0 or x1 >= len(inp[0]) or y1 < 0 or y1 >= len(inp):
continue
if d not in queue:
inp[y1][x1] += 1
if inp[y1][x1] > 9:
queue.append(d)
if step in [193, 194, 195]:
verbose(f"{step = }")
verbose(f"{len(queue) = }")
for row in inp:
verbose(str(row))
if part == 2 and len(queue) == len(inp) * len(inp[0]):
return step
verbose(f"{len(queue) = }")
for row in inp:
verbose(str(row))
if grid:
return inp
return res
if __name__ == "__main__":
VERBOSE = False
print(result(get_input(), part = 2))

10
2021/11/sample_p1 Normal file
View File

@ -0,0 +1,10 @@
5483143223
2745854711
5264556173
6141336146
6357385478
4167524645
2176841721
6882881134
4846848554
5283751526

61
2021/11/test.py Normal file
View File

@ -0,0 +1,61 @@
from prog import *
import unittest
class Tests(unittest.TestCase):
def test_part1_grid(self):
self.assertEqual(result([
[1, 1, 1, 1, 1],
[1, 9, 9, 9, 1],
[1, 9, 1, 9, 1],
[1, 9, 9, 9, 1],
[1, 1, 1, 1, 1],
], grid = True, steps = 1), [
[3, 4, 5, 4, 3],
[4, 0, 0, 0, 4],
[5, 0, 0, 0, 5],
[4, 0, 0, 0, 4],
[3, 4, 5, 4, 3],
])
self.assertEqual(result([
[1, 1, 1, 1, 1],
[1, 9, 9, 9, 1],
[1, 9, 1, 9, 1],
[1, 9, 9, 9, 1],
[1, 1, 1, 1, 1],
], grid = True, steps = 2), [
[4, 5, 6, 5, 4],
[5, 1, 1, 1, 5],
[6, 1, 1, 1, 6],
[5, 1, 1, 1, 5],
[4, 5, 6, 5, 4],
])
def test_part1(self):
self.assertEqual(result([
[1, 1, 1, 1, 1],
[1, 9, 9, 9, 1],
[1, 9, 1, 9, 1],
[1, 9, 9, 9, 1],
[1, 1, 1, 1, 1],
], steps = 1), 9)
self.assertEqual(result([
[1, 1, 1, 1, 1],
[1, 9, 9, 9, 1],
[1, 9, 1, 9, 1],
[1, 9, 9, 9, 1],
[1, 1, 1, 1, 1],
], steps = 2), 9)
self.assertEqual(result(get_input(sample = True), steps = 10), 204)
self.assertEqual(result(get_input(sample = True)), 1656)
def test_part2(self):
self.assertEqual(result(get_input(sample = True), part = 2), 195)