#!/usr/bin/env python3
"""Reproduce the 68.9% figure on https://hexboardgen.com/random-catan-boards

200,000 random deals of Catan's 18 number tokens onto the 19-hex board
(one desert, no token). Counts adjacent 6/8 pairs.

Run: python3 deal.py          -> prints the table in /data/random-boards.csv
Python 3.8+. Same CPython seed => same counts.
"""
import random

ROWS = [3, 4, 5, 4, 3]                      # the 19-hex base board, row by row
DIRS = ((1, 0), (1, -1), (0, -1), (-1, 0), (-1, 1), (0, 1))  # axial neighbours
TOKENS = [2, 3, 3, 4, 4, 5, 5, 6, 6, 8, 8, 9, 9, 10, 10, 11, 11, 12]
RUNS, SEED = 200_000, 7


def board():
    cells, mid = [], (len(ROWS) - 1) / 2
    for ri, n in enumerate(ROWS):
        r = ri - mid
        q0 = max(-mid, -mid - r)
        cells += [(q0 + k, r) for k in range(n)]
    return cells


CELLS = board()
IDX = {c: i for i, c in enumerate(CELLS)}
NB = [[IDX[(c[0] + a, c[1] + b)] for a, b in DIRS if (c[0] + a, c[1] + b) in IDX] for c in CELLS]


def one(rng):
    nums = TOKENS[:]
    rng.shuffle(nums)
    desert = rng.randrange(len(CELLS))
    place, k = {}, 0
    for i in range(len(CELLS)):
        if i == desert:
            place[i] = None
        else:
            place[i] = nums[k]
            k += 1
    return sum(1 for i in range(len(CELLS)) for j in NB[i]
               if i < j and {place[i], place[j]} == {6, 8})


def main():
    rng = random.Random(SEED)
    counts = [0] * 6
    for _ in range(RUNS):
        counts[min(one(rng), 5)] += 1
    print("pairs,layouts,share,cumulative")
    cum = 0
    for pairs, n in enumerate(counts):
        cum += n
        print(f"{pairs},{n},{n/RUNS:.4f},{cum/RUNS:.4f}")
    hit = RUNS - counts[0]
    print(f"# P(>=1 adjacent 6/8) = {hit/RUNS:.4f} over {RUNS} deals")


if __name__ == "__main__":
    main()
