"""The champagne tower: Pascal's triangle with glasses that hold one unit.

Part 1 of the Pascal puzzles, https://slow-is-smooth.io/blog/pascal-puzzles-the-champagne-tower/

Champagne is poured into the top glass of a tower. A glass holds `capacity` units (1 unless said
otherwise); whatever it receives beyond that runs over and is shared among the glasses below it.
In the triangle each glass rests on two, and each gets half. A glass in the bottom row spills onto
the table.

A tower is a pair (glasses, children): `glasses` lists every glass with the top first and every
glass after the glasses above it, and `children[g]` lists (glass below, share), the shares summing
to 1. Nothing here depends on the shape, so the same code runs the triangle, the square pyramid
that real towers are, and towers of glasses of different sizes.

Every function takes a `number` type: Fraction for exact answers, float for what most code uses.
Standard library only.
"""
from fractions import Fraction
from math import comb


# ---------------------------------------------------------------- towers

def triangle(rows):
    """Glass (r, c) for 0 <= c <= r < rows, resting on (r+1, c) and (r+1, c+1) below it."""
    glasses = [(r, c) for r in range(rows) for c in range(r + 1)]
    half = Fraction(1, 2)
    children = {(r, c): [((r + 1, c), half), ((r + 1, c + 1), half)] if r + 1 < rows else []
                for r, c in glasses}
    return glasses, children


def square_pyramid(layers):
    """Glass (l, i, j) for 0 <= i, j <= l < layers, over the four glasses (l+1, i..i+1, j..j+1)."""
    glasses = [(l, i, j) for l in range(layers) for i in range(l + 1) for j in range(l + 1)]
    quarter = Fraction(1, 4)
    children = {(l, i, j): [((l + 1, i + a, j + b), quarter) for a in (0, 1) for b in (0, 1)]
                if l + 1 < layers else [] for l, i, j in glasses}
    return glasses, children


# ---------------------------------------------------------------- pouring a fixed amount

def champagne_tower(poured, query_row, query_glass):
    """How full glass (query_row, query_glass) is after `poured` glasses: the interview version."""
    flow = [poured]                       # what reaches each glass of the current row
    for _ in range(query_row):
        below = [0.0] * (len(flow) + 1)
        for c, amount in enumerate(flow):
            extra = max(0.0, amount - 1) / 2
            below[c] += extra
            below[c + 1] += extra
        flow = below
    return min(1.0, flow[query_glass])


def pour(tower, poured, capacity=None, number=Fraction):
    """Pour `poured` into the top of any tower. Returns (inflow per glass, amount on the table).

    Glasses are visited top down, so each one has received everything it will before it is
    visited. Its level is min(inflow, capacity), and inflow - capacity runs over."""
    glasses, children = tower
    zero = number(0)
    inflow = {g: zero for g in glasses}
    inflow[glasses[0]] = number(poured)
    table = zero
    for g in glasses:
        excess = inflow[g] - (number(1) if capacity is None else number(capacity[g]))
        if excess > 0:
            if children[g]:
                for h, share in children[g]:
                    inflow[h] += excess * number(share)
            else:
                table += excess
    return inflow, table


def levels(tower, poured, capacity=None, number=Fraction):
    """How much each glass holds after `poured` has gone in."""
    inflow, _ = pour(tower, poured, capacity, number)
    return {g: min(q, number(1) if capacity is None else number(capacity[g])) for g, q in inflow.items()}


def pascal_flow(rows, poured):
    """The tower with bottomless glasses: everything passes on, so row r gets poured * C(r, c) / 2^r."""
    return {(r, c): Fraction(poured) * comb(r, c) / 2 ** r for r in range(rows) for c in range(r + 1)}


def kept_formula(rows, poured, level):
    """Inflow to every glass of the triangle, from the pour and what each glass above keeps:

        inflow(r, c) = poured * C(r, c) / 2^r  -  sum over (i, j) above of level(i, j) * C(r-i, c-j) / 2^(r-i)

    Pascal's share of the pour, minus Pascal's share of everything the glasses above hold back."""
    out = {}
    for r in range(rows):
        for c in range(r + 1):
            q = Fraction(poured) * comb(r, c) / 2 ** r
            for i in range(r):
                for j in range(max(0, c - (r - i)), min(i, c) + 1):
                    q -= level[(i, j)] * comb(r - i, c - j) / Fraction(2) ** (r - i)
            out[(r, c)] = q
    return out


# ---------------------------------------------------------------- pouring until every glass is full

def fill_events(tower, capacity=None, number=Fraction):
    """Pour steadily and record when each glass becomes full: [(poured so far, [glasses])].

    Between two events nothing changes but the levels: the top receives 1 per unit poured, a full
    glass passes on everything it receives, and a glass that isn't full keeps all of it. So every
    rate is fixed until the next glass fills, and that glass is the one with the least
    (room left) / (rate). Step to it, fill it, recompute the rates, repeat. With Fraction every
    moment is exact; with float, the same arithmetic in doubles."""
    glasses, children = tower
    zero, one = number(0), number(1)
    cap = {g: one if capacity is None else number(capacity[g]) for g in glasses}
    level = {g: zero for g in glasses}
    full = set()
    poured = zero
    events = []
    while len(full) < len(glasses):
        rate = {g: zero for g in glasses}
        rate[glasses[0]] = one
        for g in glasses:                        # top down: a glass's rate is final when visited
            if g in full:
                for h, share in children[g]:
                    rate[h] += rate[g] * number(share)
        step = min((cap[g] - level[g]) / rate[g] for g in glasses if g not in full and rate[g] > 0)
        poured += step
        filled = []
        for g in glasses:
            if g not in full and rate[g] > 0:
                if (cap[g] - level[g]) / rate[g] == step:
                    level[g] = cap[g]
                    filled.append(g)
                else:
                    level[g] += rate[g] * step
        full.update(filled)
        events.append((poured, filled))
    return events


def fill_pours(tower, capacity=None, number=Fraction):
    """The amount that must be poured to fill each glass."""
    return {g: p for p, gs in fill_events(tower, capacity, number) for g in gs}


def fill_pour_by_bisection(tower, glass, capacity=None, number=Fraction, steps=60):
    """The same answer for one glass, by halving an interval: a glass's level only rises as more is
    poured, so 'is it full yet?' flips from no to yes exactly once."""
    lo, hi = number(0), number(1)
    while levels(tower, hi, capacity, number)[glass] < (1 if capacity is None else capacity[glass]):
        hi *= 2
    for _ in range(steps):
        mid = (lo + hi) / 2
        if levels(tower, mid, capacity, number)[glass] < (1 if capacity is None else capacity[glass]):
            lo = mid
        else:
            hi = mid
    return lo, hi


def cone_formula(r, c):
    """Fill pour of (r, c) if every glass above it that can reach it is already full when it fills:
    set its inflow to 1 in kept_formula with all those levels 1, and solve for the pour."""
    total = Fraction(2) ** r
    for i in range(r):
        for j in range(max(0, c - (r - i)), min(i, c) + 1):
            total += comb(r - i, c - j) * Fraction(2) ** i
    return total / comb(r, c)


def ancestors(r, c):
    """Every glass above (r, c) from which champagne can reach it."""
    return [(i, j) for i in range(r) for j in range(max(0, c - (r - i)), min(i, c) + 1)]
