"""Check of the counterexample to the Odd Sum conjecture of Ahmed and Snevily at n = 17.

This script uses only the standard library.

1. The script calculates t(pi) with two methods. The first method uses the definition:
   the sum of the run counts over all subsequences of length >= 3. The second method uses
   the O(n^3) formula with turning points. The two results must be equal.
2. The permutation below has t = 798783. This is the proved value of tmax(17).
3. The permutation violates the Odd Sum conjecture: pi_4 + pi_14 is even.

The scripts optimum_cpsat.py and optimum_highs.py prove that 798783 is the maximum.
"""
import itertools, random
from t_definition import t as t_def
from t_formula import t as t_fast

PI = [8, 14, 3, 15, 6, 10, 2, 17, 7, 12, 1, 16, 5, 11, 4, 13, 9]
TMAX17 = 798783

for n in range(3, 8):                      # exhaustive agreement of the two formulas
    assert all(t_def(p) == t_fast(p) for p in itertools.permutations(range(1, n + 1)))
rng = random.Random(0)
for _ in range(10):
    p = list(range(1, 14)); rng.shuffle(p); assert t_def(p) == t_fast(p)
published = {3: 2, 4: 11, 5: 37, 6: 106, 7: 270, 8: 653, 9: 1523}   # Ahmed-Snevily
for n, v in published.items():
    assert max(t_fast(p) for p in itertools.permutations(range(1, n + 1))) == v

# The sets RC(3), ..., RC(6) from Example 1.4 of Adamczak, arXiv:1605.02415.
PUBLISHED_RC = {
    3: '132 213 231 312',
    4: '2143 2413 3142 3412',
    5: '24153 25143 31524 32514 34152 35142 41523 42513',
    6: '326154 351624 426153 451623',
}
for n, text in PUBLISHED_RC.items():
    perms = list(itertools.permutations(range(1, n + 1)))
    best = max(t_def(p) for p in perms)
    rc = sorted(''.join(map(str, p)) for p in perms if t_def(p) == best)
    assert rc == sorted(text.split()), n
print('RC(3), RC(4), RC(5), RC(6) are equal to the published sets.')

assert sorted(PI) == list(range(1, 18))
assert t_fast(PI) == TMAX17
assert t_def(PI) == TMAX17                 # straight from the definition, all 2^17 subsequences
sums = [PI[j] + PI[16 - j] for j in range(8)]
print('pair sums pi_j + pi_{18-j}, j=1..8:', sums)
bad = [(j + 1, s) for j, s in enumerate(sums) if s % 2 == 0]
assert bad, 'no violation'
print('t(pi) =', t_def(PI), '= tmax(17); even pair sums at j =', bad, '. The permutation violates the Odd Sum conjecture.')
