# Independent replay of isitsolved collatz.json: total stopping time T(n) (number of
# 3n+1 / n/2 steps to reach 1) for every n <= N, and the records (n with T(n) > T(m) for all m<n).
import json, sys, hashlib
path = sys.argv[1]
raw = open(path, 'rb').read()
d = json.loads(raw)
N = d['N']
def T(n, memo={1: 0}):
    path = []
    while n not in memo:
        path.append(n)
        n = n // 2 if n % 2 == 0 else 3 * n + 1
    t = memo[n]
    for m in reversed(path):
        t += 1
        if m <= 3 * N: memo[m] = t
    return t
mine = [T(n) for n in range(1, N + 1)]
# naive cross-check (no memo) on a sample
def Tnaive(n):
    s = 0
    while n != 1:
        n = n // 2 if n % 2 == 0 else 3 * n + 1; s += 1
    return s
assert all(mine[n-1] == Tnaive(n) for n in list(range(1, 5001)) + list(range(N - 5000, N + 1)))
theirs = d['steps']
print("sha256 of file:", hashlib.sha256(raw).hexdigest())
print("N =", N, " len(steps) =", len(theirs))
diff = [n for n in range(1, N + 1) if mine[n-1] != theirs[n-1]]
print("mismatching n:", len(diff), diff[:10])
print("sum T(n): mine", sum(mine), " theirs", sum(theirs), "  max:", max(mine), "at n =", mine.index(max(mine)) + 1)
rec, best = [], -1
for n in range(1, N + 1):
    if mine[n-1] > best:
        best = mine[n-1]; rec.append({'n': n, 'steps': best})
print("records: mine", len(rec), " theirs", len(d['records']), " identical:", rec == d['records'])
print("last records:", rec[-4:])
