summaryrefslogtreecommitdiff
path: root/14_2023.py
blob: c7930cee7b9290a017e67b6869c4cfdc8d86e157 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import sys
import re
from copy import deepcopy
from math import gcd
from collections import defaultdict, Counter, deque

D = open(sys.argv[1]).read().strip()
L = D.split("\n")
G = [[c for c in row] for row in L]


def rotate(G):
    R = len(G)
    C = len(G[0])
    NG = [["?" for _ in range(R)] for _ in range(C)]
    for r in range(R):
        for c in range(C):
            NG[c][R - 1 - r] = G[r][c]
    return NG


def roll(G):
    R = len(G)
    C = len(G[0])
    for c in range(C):
        for _ in range(R):
            for r in range(R):
                if G[r][c] == "O" and r > 0 and G[r - 1][c] == ".":
                    G[r][c] = "."
                    G[r - 1][c] = "O"
    return G


def score(G):
    ans = 0
    R = len(G)
    C = len(G[0])
    for r in range(R):
        for c in range(C):
            if G[r][c] == "O":
                ans += len(G) - r
    return ans


def show(G):
    for r in range(len(G)):
        print("".join(G[r]))


BY_GRID = {}

target = 10**9
t = 0
while t < target:
    t += 1
    for j in range(4):
        G = roll(G)
        if t == 1 and j == 0:
            print(score(G))
        G = rotate(G)
    Gh = tuple(tuple(row) for row in G)
    if Gh in BY_GRID:
        cycle_length = t - BY_GRID[Gh]
        amt = (target - t) // cycle_length
        t += amt * cycle_length
    BY_GRID[Gh] = t
print(score(G))