"""Minimax equilibrium of one round of the number game. Picker picks x in 1..N (mixed). Guesser picks a search tree (mixed). Guess below x costs LOW, above x costs HIGH, hit costs 0. Solved exactly by column generation: LP over trees found so far, best-response tree by interval DP.""" import numpy as np from scipy.optimize import linprog N, LOW, HIGH = 100, 3, 1 def best_tree(p): """Return (cost vector per x, expected cost) of best-response tree to p.""" P = np.concatenate([[0], np.cumsum(p)]) S = lambda i, j: P[j] - P[i - 1] if j >= i else 0.0 C = np.zeros((N + 2, N + 2)); R = np.zeros((N + 2, N + 2), int) for length in range(1, N + 1): for i in range(1, N - length + 2): j = i + length - 1 best, br = 1e18, i for r in range(i, j + 1): v = C[i][r - 1] + C[r + 1][j] + HIGH * S(i, r - 1) + LOW * S(r + 1, j) if v < best: best, br = v, r C[i][j], R[i][j] = best, br cost = np.zeros(N) def walk(i, j, acc): if i > j: return r = R[i][j]; cost[r - 1] = acc walk(i, r - 1, acc + HIGH); walk(r + 1, j, acc + LOW) walk(1, N, 0) return cost, C[1][N] trees = [best_tree(np.ones(N) / N)[0]] while True: A = np.array(trees) # trees x numbers k = len(trees) # picker: max v s.t. A p >= v, sum p = 1, p >= 0 (vars p..., v) c = np.zeros(N + 1); c[-1] = -1 A_ub = np.hstack([-A, np.ones((k, 1))]); b_ub = np.zeros(k) A_eq = np.hstack([np.ones((1, N)), [[0]]]) res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=[1], bounds=[(0, None)] * N + [(None, None)], method="highs") p, v = res.x[:N], res.x[-1] q = -res.ineqlin.marginals # guesser's mix over trees cost, br = best_tree(p) if br >= v - 1e-9: break trees.append(cost) print(f"game value (guesser's expected cost): {v:.4f}") print(f"trees generated: {len(trees)}, used by guesser: {(q > 1e-6).sum()}") print("picker's equilibrium distribution (numbers with prob > 0.5%):") for x in np.argsort(-p): if p[x] > 0.005: print(f" {x+1:3d}: {p[x]*100:5.2f}%") print(f"prob mass on 90-100: {p[89:].sum()*100:.1f}%, on 1-50: {p[:50].sum()*100:.1f}%") # guesser's opening guess distribution roots = {} for t, w in zip(trees, q): if w > 1e-6: r = int(np.where(t == 0)[0][0]) + 1 roots[r] = roots.get(r, 0) + w print("guesser's first guess:", {k: round(v*100, 1) for k, v in sorted(roots.items())}) # worst cost of a pure strategy picking a single number vs equilibrium guesser exp_by_x = np.array(trees).T @ q print(f"cost to guesser for each number under its mix: min {exp_by_x.min():.3f}, max {exp_by_x.max():.3f}") import json json.dump({"value": v, "picker": [round(float(x), 6) for x in p], "first_guess": {str(k): round(float(w), 6) for k, w in sorted(roots.items())}}, open("equilibrium.json", "w"), indent=1)