# -*- coding: utf-8 -*-
"""2023年度 女子学院 (JG-E0019) の独立検証。主解法 (てんびん・角度の定石・周期の表・さいころの面の表) とは別経路
(sympy の連立方程式・座標とベクトルの恒等式・極座標の厳密積分・全探索シミュレーション・回転写像) で答えを再計算する。浮動小数は使わない。"""
from fractions import Fraction as F
import itertools, sympy as sp

CHECKS = {}
R = sp.Rational

def mixed(fr):
    """Fraction → 帯分数の文字列 ('9と3/4', '21と4/9', '6')。"""
    fr = F(fr); n, d = fr.numerator, fr.denominator
    if d == 1: return str(n)
    w, r = divmod(n, d)
    return f"{w}と{r}/{d}" if w else f"{r}/{d}"

def dec2(fr):
    """分母が 100 の約数の Fraction → 小数 2 桁の文字列 ('4.95')。"""
    fr = F(fr); n, d = fr.numerator, fr.denominator
    assert 100 % d == 0, fr
    v = n * (100 // d); return f"{v // 100}.{v % 100:02d}"

def hms(sec):
    """0 時からの秒数 → 'H時M分S秒'。"""
    sec = int(sec); h, rem = divmod(sec, 3600); m, s = divmod(rem, 60); return f"{h}時{m}分{s}秒"

# ---- 大問1 ----
def q1s1():
    x = sp.Symbol("x")
    left = ((R(9, 2) - R(1, 4)) / R(3, 4) - R(17, 15)) * (R(323, 8) - R(425, 12))
    sol = sp.solve(sp.Eq(left / (x - R(11, 45)), 2023), x)
    assert len(sol) == 1
    return F(str(sol[0]))
CHECKS["JG-E0019-Q01-S01"] = {"method": "sympy で方程式 (左辺) ÷ (x − 11/45) = 2023 を直接解く (手順どおりの逆算とは別経路)", "compute": q1s1,
                              "extra": [(lambda: ((F(9, 2) - F(1, 4)) / F(3, 4) - F(17, 15)) * (F(323, 8) - F(425, 12)) / (F(23, 90) - F(11, 45)) == 2023, "x = 23/90 を元の式に再代入して 2023 になる")]}

def q1s2():
    a, b = sp.symbols("a b")
    sol = sp.solve([sp.Eq(3 * a + 2 * b, R(118, 10) * 5), sp.Eq(a + 3 * b, 9 * 4)], [a, b])
    return f"{sol[a]}%、{sol[b]}%"
CHECKS["JG-E0019-Q01-S02"] = {"method": "食塩の量の式 3a+2b=59, a+3b=36 を sympy の連立方程式として解く (てんびんとは別経路)", "compute": q1s2,
                              "expect": "15%、7%", "official_value": "15%、7%"}

def q1s3():
    r1 = lambda x: (x * 10 + F(1, 2)).__floor__() / F(10)       # 小数第 2 位を四捨五入
    r0 = lambda x: (x + F(1, 2)).__floor__()                      # 小数第 1 位を四捨五入
    r10 = lambda x: (x / 10 + F(1, 2)).__floor__() * 10           # 一の位を四捨五入
    # ①: 4.000〜5.999 を 0.001 刻みで全探索 (範囲の端は 0.01 刻みなので十分細かい)
    ok = [F(k, 1000) for k in range(4000, 6000) if r1(F(k, 1000)) == 5]
    lo, hi = min(ok), max(ok) + F(1, 1000)
    assert r1(lo - F(1, 1000)) != 5 and r1(hi) != 5 and len(ok) == 100
    # ②: 整数 N を 1〜20000 で全探索 (N×2.5≒5000 なので N≒2000、範囲は十分)
    Ns = [N for N in range(1, 20001) if r10(F(N) / F(2, 5)) == 5000 and r0(F(N, 6)) == 334]
    return f"① {dec2(lo)}以上、{dec2(hi)}未満 ② {'、'.join(map(str, Ns))}"
CHECKS["JG-E0019-Q01-S03"] = {"method": "①は 0.001 刻みの全探索で四捨五入の範囲の端を確定、②は整数を全探索して 2 条件を再代入", "compute": q1s3,
                              "expect": "① 4.95以上、5.05未満 ② 2001", "official_value": "① 4.95以上、5.05未満 ② 2001"}

def q1s4():
    s = sp.sqrt(3)
    # ア: 座標 A(0,1), B(0,0), E(1/2, 1−√3/2) で角 ABE の cos を作り、整数度の cos と厳密比較
    A, B, E = sp.Matrix([0, 1]), sp.Matrix([0, 0]), sp.Matrix([R(1, 2), 1 - s / 2])
    u, v = A - B, E - B
    cosv = u.dot(v) / sp.sqrt(u.dot(u) * v.dot(v))
    a_deg = next(d for d in range(1, 180) if sp.simplify(sp.sqrtdenest(cosv) - sp.cos(sp.rad(d))) == 0)
    # イ・ウ: 23° を一般の θ (T = tanθ) にして、ベクトルの tan の恒等式で角を確認する (合同の論法とは別経路)
    T = sp.Symbol("T", positive=True)
    C, Fp, G = sp.Matrix([1, 0]), sp.Matrix([R(1, 2), -s / 2]), sp.Matrix([R(3, 2), -s / 2])   # ひし形 BFGC (辺 1、F の内角 120°)
    X = sp.Matrix([3 * T / (3 * T + s), -s * T / (3 * T + s)])      # 対角線 BG と「C を通り傾き T の直線 LC」の交点
    assert sp.simplify(X[0] * (-s / 2) - X[1] * R(3, 2)) == 0 and sp.simplify(X[1] - T * (X[0] - 1)) == 0
    tan_between = lambda p, q: sp.Abs(p[0] * q[1] - p[1] * q[0]) / p.dot(q)     # 2 ベクトルのなす角 (0〜180°) の tan
    theta = 23
    assert sp.simplify(tan_between(Fp - X, G - X) - (s * T + 1) / (s - T)) == 0               # tan∠FXG = tan(θ+30°)
    assert sp.simplify(tan_between(sp.Matrix([-1, -T]), G - C) - (-s - T) / (1 - s * T)) == 0   # tan∠LCG = tan(120°−θ)
    return f"ア {a_deg}、イ {120 - theta}、ウ {theta + 30}"
CHECKS["JG-E0019-Q01-S04"] = {"method": "座標 (正方形 1 辺 1) でアの cos を厳密比較し、イ・ウは 23° を一般の θ にしたベクトルの tan 恒等式 (θ+30°, 120°−θ) を sympy で証明", "compute": q1s4,
                              "expect": "ア 75、イ 97、ウ 53", "official_value": "ア 75、イ 97、ウ 53"}

def l_shape(n):
    cubes = set()
    for layer in range(n):              # layer 0 が最下段 (腕の長さ n)、上に行くほど腕が 1 ずつ短い L 字
        arm = n - layer
        for i in range(arm): cubes.add((i, 0, layer)); cubes.add((0, i, layer))
    return cubes
def surface(cubes):
    d = [(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)]
    return sum(1 for (x, y, z) in cubes for (dx, dy, dz) in d if (x + dx, y + dy, z + dz) not in cubes)
def q1s5():
    c3, c10 = l_shape(3), l_shape(10)
    assert [len(l_shape(n)) for n in (1, 2, 3)] == [1, 4, 9]       # 図の 1 段・2 段・3 段の個数 (1, 1+3, 1+3+5)
    return f"表面積 {surface(c3)}cm²、体積 {len(c3)}cm³、表面積 {surface(c10)}cm²、体積 {len(c10)}cm³"
CHECKS["JG-E0019-Q01-S05"] = {"method": "立方体の座標を全列挙し、隣に立方体のない面を 1 つずつ数える (投影図の数え方とは別経路)", "compute": q1s5,
                              "expect": "表面積 34cm²、体積 9cm³、表面積 258cm²、体積 100cm³", "official_value": "表面積 34cm²、体積 9cm³、表面積 258cm²、体積 100cm³"}

# ---- 大問2 ----
def q2s1():
    a, b, c = sp.symbols("a b c")
    sol = sp.solve([sp.Eq(a + b + c, 26), sp.Eq(b - a, 10), sp.Eq(b - c, 12)], [a, b, c])
    return f"あ {sol[a]}cm、い {sol[b]}cm、う {sol[c]}cm"
CHECKS["JG-E0019-Q02-S01"] = {"method": "3 本の条件式を sympy の連立方程式として解く (和差算とは別経路)", "compute": q2s1,
                              "expect": "あ 6cm、い 16cm、う 4cm", "official_value": "あ 6cm、い 16cm、う 4cm"}

def q2s2():
    r, th = sp.symbols("r theta", positive=True)
    sector = lambda radius, th0, th1: sp.integrate(sp.integrate(r, (r, 0, radius)), (th, th0, th1))   # 極座標で厳密積分
    # い (1 辺 16): 中心 O、対角線の向きは (±1, ±1) → 45°, 135°, 225°, 315°。中心から下辺の中点へは 270°。網目 = [135°,225°] ∪ [225°,270°]
    diag = sorted(sp.atan2(y, x) % (2 * sp.pi) for (x, y) in [(1, 1), (-1, 1), (-1, -1), (1, -1)])
    assert diag == [sp.pi / 4, 3 * sp.pi / 4, 5 * sp.pi / 4, 7 * sp.pi / 4]
    big = sector(R(16, 2), diag[1], diag[2]) + sector(R(16, 2), diag[2], 3 * sp.pi / 2)
    # あ (1 辺 6): 中心は あ の右下の頂点、弧は左下の頂点 (180°) → 右上の頂点 (90°)。う (1 辺 4): 中心は左下の頂点、弧は 90° → 0°
    qa = sector(6, sp.pi / 2, sp.pi); qc = sector(4, 0, sp.pi / 2)
    total = sp.simplify(big + qa + qc)
    assert total == 37 * sp.pi
    return F(str(total.subs(sp.pi, R(314, 100))))
CHECKS["JG-E0019-Q02-S02"] = {"method": "網目の各部分を極座標の二重積分で厳密に求め (角の範囲は座標から)、37π を確認して π=3.14 を代入", "compute": q2s2}

# ---- 大問3 ----
ORDER = "ABCDEDCB"
def lamp_state(n):
    cnt = {c: 0 for c in "ABCDE"}
    for i in range(n): cnt[ORDER[i % 8]] += 1
    return frozenset(c for c in "ABCDE" if cnt[c] % 2 == 1)
def q3s1():
    assert lamp_state(10) == {"B", "E"}            # 本文の例 (10 回目で B と E) と一致
    lit = 0
    for n in range(1, 10000):                        # C の 10 回目の点灯は高々 8×10 回以内なので十分
        if ORDER[(n - 1) % 8] == "C" and "C" in lamp_state(n):
            lit += 1
            if lit == 10: return n
CHECKS["JG-E0019-Q03-S01"] = {"method": "押す操作を 1 回ずつシミュレーションし、C が点灯する回を数える (周期の式とは別経路)", "compute": q3s1}
CHECKS["JG-E0019-Q03-S02"] = {"method": "150 回の押下をシミュレーションして点灯中のランプを列挙", "compute": lambda: "、".join(sorted(lamp_state(150))),
                              "expect": "A、B、C、E", "official_value": "A、B、C、E"}
CHECKS["JG-E0019-Q03-S03"] = {"method": "1〜200 回のすべての状態を全列挙し {B, C} ちょうどになる回を数える", "compute": lambda: sum(1 for n in range(1, 201) if lamp_state(n) == {"B", "C"}),
                              "extra": [(lambda: [n for n in range(1, 201) if lamp_state(n) == {"B", "C"}] == [14 + 16 * k for k in range(12)], "該当回は 14, 30, …, 190 (16 ごと)")]}

# ---- 大問4 ----
def q4s1():
    pts = [sp.Matrix(p) for p in [(0, 3), (4, 0), (4, 4), (8, 4), (8, 0), (11, 4)]]   # B, C, D, E, F, G (A は原点)
    A, B = sp.Matrix([0, 0]), pts[0]
    segs = []; t0 = sp.Integer(0)
    for P0, P1 in zip(pts, pts[1:]):
        L = sp.sqrt((P1 - P0).dot(P1 - P0)); assert L.is_integer       # 5, 4, 4, 4, 5
        segs.append((t0, t0 + L, P0, P1)); t0 += L
    assert t0 == 22
    shoelace = lambda P: sp.Abs(A[0] * (B[1] - P[1]) + B[0] * (P[1] - A[1]) + P[0] * (A[1] - B[1])) / 2
    def pos(t):
        for a, b, P0, P1 in segs:
            if a <= t <= b: return P0 + (P1 - P0) * (t - a) / (b - a)
    y_low, y_up = shoelace(pos(3)), shoelace(pos(R(23, 2)))
    t = sp.Symbol("t")
    a, b, P0, P1 = segs[-1]; P = P0 + (P1 - P0) * (t - a) / (b - a)
    signed = (A[0] * (B[1] - P[1]) + B[0] * (P[1] - A[1]) + P[0] * (A[1] - B[1])) / 2      # 符号つき面積 (向きにより負)
    sol = [v for sgn in (16, -16) for v in sp.solve(sp.Eq(signed, sgn), t) if a <= v <= b]
    assert len(sol) == 1 and all(shoelace(pos(tt)) < 16 for tt in (5, 9, 13, 17))   # 16 に達するのは最後の辺 FG 上だけ
    return f"(縦軸・上) {mixed(F(str(y_up)))}、(縦軸・下) {mixed(F(str(y_low)))}、(横軸) {mixed(F(str(sol[0])))}"
CHECKS["JG-E0019-Q04-S01"] = {"method": "折れ線上の P(t) を座標で表し、三角形 ABP の面積を靴ひも公式で計算。面積 16 の時刻は sympy で方程式を解く (横の速さの議論とは別経路)", "compute": q4s1,
                              "expect": "(縦軸・上) 9と3/4、(縦軸・下) 3と3/5、(横軸) 21と4/9", "official_value": "(縦軸・上) 9と3/4、(縦軸・下) 3と3/5、(横軸) 21と4/9"}

# ---- 大問5 ----
def share(k, total=2023):
    """J, G, G, J の順に k 枚ずつ取り、端数は次の番の人が取る。(J, G) の枚数。"""
    who = lambda t: "J" if t % 4 in (1, 0) else "G"
    J = G = 0; full, rem = divmod(total, k)
    for t in range(1, full + 1):
        if who(t) == "J": J += k
        else: G += k
    if rem:
        if who(full + 1) == "J": J += rem
        else: G += rem
    return J, G
def q5s1():
    assert share(20) == (1020, 1003) and share(30) == (1003, 1020)   # 本文の例で手順を確認
    return share(23)[0]
CHECKS["JG-E0019-Q05-S01"] = {"method": "取る操作を 1 回ずつシミュレーション (本文の例 20 枚・30 枚で手順を確認)", "compute": q5s1}
def q5s2():
    # 2 以上 2023 以下のすべての素数を全探索。2024 以上なら 1 回目で J が全部 (2023 枚) 取るので候補にならない
    sols = [k for k in range(2, 2024) if sp.isprime(k) and share(k)[0] == 1023]
    assert len(sols) == 1; return sols[0]
CHECKS["JG-E0019-Q05-S02"] = {"method": "2023 以下のすべての素数についてシミュレーションし J = 1023 になるものを全探索 (一意性も確認)", "compute": q5s2}

# ---- 大問6 ----
def roll(faces, m):
    """面 (方向ベクトル → 目) を 90° 回転。右へ転がす: (x,y,z)→(z,y,−x)、下 (手前 −y) へ転がす: (x,y,z)→(x,−z,y)。"""
    rot = (lambda v: (v[2], v[1], -v[0])) if m == "右" else (lambda v: (v[0], -v[2], v[1]))
    return {rot(v): f for v, f in faces.items()}
START = {(0, 0, 1): 2, (0, 0, -1): 5, (0, -1, 0): 1, (0, 1, 0): 6, (1, 0, 0): 3, (-1, 0, 0): 4}   # 図 2: 上 2、手前 1、右 3
def top_sum(path):
    d = dict(START); s = d[(0, 0, 1)]
    for m in path: d = roll(d, m); s += d[(0, 0, 1)]
    return s
def paths(): return sorted(set("".join(p) for p in itertools.permutations("右右右下下")))   # 右 3・下 2 の全順列 (重複除去)
CHECKS["JG-E0019-Q06-S01"] = {"method": "右 3 回・下 2 回の並べ方を itertools で全列挙して重複を除き数える", "compute": lambda: len(paths())}
def q6s2():
    assert all(START[v] + START[(-v[0], -v[1], -v[2])] == 7 for v in START)   # 向かい合う面の和 7
    assert roll(START, "右")[(0, 0, 1)] == START[(-1, 0, 0)] and roll(START, "下")[(0, 0, 1)] == START[(0, 1, 0)]  # 右で左の面、下で奥の面が上に
    return top_sum("右右下右下")
CHECKS["JG-E0019-Q06-S02"] = {"method": "面を方向ベクトルで持ち、90° 回転写像で 5 回転がして上の面の和を計算 (面の表とは別経路)", "compute": q6s2}
def q6s3():
    target = top_sum("右右下右下")
    others = [p for p in paths() if p != "右右下右下" and top_sum(p) == target]
    return f"{' または '.join(others)} ({len(others)} 通りのいずれか)"
CHECKS["JG-E0019-Q06-S03"] = {"method": "10 通りの経路すべてを回転写像で計算し、図 3 と同じ和になる経路を全列挙", "compute": q6s3,
                              "expect": "下下右右右 または 右右下下右 (2 通りのいずれか)", "official_value": "下下右右右 または 右右下下右 (2 通りのいずれか)"}

# ---- 大問7 ----
def q7s1():
    # 月曜 0:00 を 0 秒とし、土曜 10:40 までの経過秒に 1 日 360 秒の遅れを比例させる
    t_mon = 0 * 86400 + 18 * 3600; t_sat = 5 * 86400 + 10 * 3600 + 40 * 60
    loss = F(360, 86400) * (t_sat - t_mon)
    shown = F(18 * 3600) + loss                 # 土曜に正しい → 月曜はその分だけ進んでいた
    assert shown.denominator == 1
    return hms(shown)
CHECKS["JG-E0019-Q07-S01"] = {"method": "秒単位の経過時間に比例定数 360/86400 を掛けて遅れを求め、月曜の表示を再構成", "compute": q7s1,
                              "expect": "18時28分10秒", "official_value": "18時28分10秒"}
def q7s2():
    x = sp.Symbol("x")                                   # B が 1 日に進む秒数
    rateA = R(-360, 86400)
    t_monA, t_tueB, t_wed = 18 * 3600, 86400 + 8 * 3600, 2 * 86400 + 20 * 3600
    showA = R(t_wed) + 600 + rateA * (t_wed - t_monA)    # 月曜 18:00 に +600 秒
    showB = R(t_wed) - 600 + x / 86400 * (t_wed - t_tueB)  # 火曜 8:00 に −600 秒
    sol = sp.solve(sp.Eq(showA, showB), x); assert len(sol) == 1
    gain = F(str(sol[0])); assert gain.denominator == 1
    return f"{int(gain) // 60}分{int(gain) % 60}秒、{hms(F(str(showA)) - 2 * 86400)}"
CHECKS["JG-E0019-Q07-S02"] = {"method": "A・B の表示を秒の一次式で表し、水曜 20:00 に等しいという方程式を sympy で解く", "compute": q7s2,
                              "expect": "5分0秒、19時57分30秒", "official_value": "5分0秒、19時57分30秒"}
