From f4d8aef7021936c2e2460457fd717f3323f01ff8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B8ren=20Rasmussen?= Date: Mon, 1 Feb 2021 08:38:55 +0100 Subject: [PATCH] Add day 11, kgn solution --- 2020/11/kgn.py | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 2020/11/kgn.py diff --git a/2020/11/kgn.py b/2020/11/kgn.py new file mode 100644 index 0000000..5e2fb39 --- /dev/null +++ b/2020/11/kgn.py @@ -0,0 +1,64 @@ +import copy + + +def mutate(seats, seatscopy, row, col, nocc, visible): + changed = False + if seats[row][col] == 'L': + if nocc == 0: + seatscopy[row][col] = '#' + changed = True + elif seats[row][col] == '#': + if nocc >= visible: + seatscopy[row][col] = 'L' + changed = True + + return changed + + +def occ(seats, numseats, seatlen, row, col, visible): + nocc = 0 + for dr in [-1, 0, 1]: + for dc in [-1, 0, 1]: + if not (dr == 0 and dc == 0): + rr = row + dr + cc = col + dc + + if visible > 4: + while 0 <= rr < numseats and 0 <= cc < seatlen and seats[rr][cc] == '.': + rr = rr + dr + cc = cc + dc + + if 0 <= rr < numseats: + if 0 <= cc < seatlen: + if seats[rr][cc] == '#': + nocc += 1 + return nocc + + +def solve(seats, visible): + numseats = len(seats) + seatlen = len(seats[0]) + while True: + seatscopy = copy.deepcopy(seats) + changed = False + for row in range(numseats): + for col in range(seatlen): + nocc = occ(seats, numseats, seatlen, row, col, visible) + changed |= mutate(seats, seatscopy, row, col, nocc, visible) + + if not changed: + break + seats = copy.deepcopy(seatscopy) + + result = 0 + for row in range(numseats): + for col in range(seatlen): + if seats[row][col] == '#': + result += 1 + return result + + +with open('data.txt', 'r') as f: + seats = [list(x.strip()) for x in f.readlines()] + print(solve(seats, 4)) + print(solve(seats, 5))