"""第8章 検算：最大ニューロンと衝突の重みで解く N-Queen（筆者が工夫して確かめた版）

Takefuji の著書（1992）の第1章、舩曵ら（1997、最大ニューロンで N-Queen）の本文は読んでいない。
ここに書くのは、第8章の四色問題で使った組み合わせ（ch08_fourcolor_maxneuron.py）を
N-Queen に当てはめた筆者の版で、論文の方法そのものではない。
（舩曵らの論文の要旨は「逐次・N 並列・N^2 並列の更新で 500-queens までシミュレーション」と報告）

  ニューロン：N×N。行 r ごとに最大ニューロン＝入力が最大の列 c に1つだけクイーンを置く。
              「各行にクイーン1つ」は構造で守られる。
  入力：      U_rc = -(w_col[c]·列 c のほかのクイーンの数 + w_d1[r-c]·同じ右下がり斜めの数
                     + w_d2[r+c]·同じ左下がり斜めの数)
              同点は今の列を優先、なければ無作為。
  更新：      非同期（行を無作為な順に1つずつ）
  局所最小：  1巡でどの行も動かず、まだ衝突があれば、衝突している列・斜めの重みを1増やす
  終了：      衝突0

使い方：python ch08_nqueens_maxneuron.py
"""
import sys
import time

import numpy as np

MAX_SWEEPS = 5000


def run(N, rng):
    col = rng.integers(0, N, N)
    w_c = np.ones(N)
    w_d1 = np.ones(2 * N - 1)                 # r - c + N - 1
    w_d2 = np.ones(2 * N - 1)                 # r + c
    cnt_c = np.bincount(col, minlength=N).astype(float)
    r_all = np.arange(N)
    cnt_d1 = np.bincount(r_all - col + N - 1, minlength=2 * N - 1).astype(float)
    cnt_d2 = np.bincount(r_all + col, minlength=2 * N - 1).astype(float)
    cs = np.arange(N)
    for sweep in range(1, MAX_SWEEPS + 1):
        moved = False
        for r in rng.permutation(N):
            c0 = col[r]
            cnt_c[c0] -= 1; cnt_d1[r - c0 + N - 1] -= 1; cnt_d2[r + c0] -= 1
            U = -(w_c * cnt_c + w_d1[r - cs + N - 1] * cnt_d1[r - cs + N - 1] + w_d2[r + cs] * cnt_d2[r + cs])
            cand = np.flatnonzero(U == U.max())
            c = c0 if c0 in cand else (int(cand[0]) if len(cand) == 1 else int(rng.choice(cand)))
            col[r] = c
            cnt_c[c] += 1; cnt_d1[r - c + N - 1] += 1; cnt_d2[r + c] += 1
            moved |= c != c0
        bad_c = cnt_c > 1
        bad_d1 = cnt_d1 > 1
        bad_d2 = cnt_d2 > 1
        if not (bad_c.any() or bad_d1.any() or bad_d2.any()):
            return sweep
        if not moved:
            w_c[bad_c] += 1; w_d1[bad_d1] += 1; w_d2[bad_d2] += 1
    return None


def check(N, col):
    return len(set(col)) == N and len({r - c for r, c in enumerate(col)}) == N and len({r + c for r, c in enumerate(col)}) == N


def main():
    print(f"Python {sys.version.split()[0]} / NumPy {np.__version__}")
    for N, trials in ((8, 100), (50, 100), (100, 50), (500, 10)):
        rng = np.random.default_rng(100)
        t0 = time.time()
        res = [run(N, rng) for _ in range(trials)]
        ok = [s for s in res if s is not None]
        line = f"{N}-Queen：解けた {len(ok)}/{trials}"
        if ok:
            line += f"、巡回数 平均 {np.mean(ok):.1f}・最大 {max(ok)}"
        print(line + f"（{time.time() - t0:.0f}秒、乱数 seed=100）", flush=True)


if __name__ == "__main__":
    main()
