"""Independent Collatz stopping-time enumeration, with compressed even runs."""
import array,json,pathlib,time
started=time.monotonic()
N=10_000_000
memo=array.array('I',[0])*(N+1)
records=[{'n':1,'delay':0}]
best=0
for n in range(2,N+1):
 x=n;steps=0
 while x>=n:
  if x&1:
   x=3*x+1
   steps+=1
  twos=(x & -x).bit_length()-1
  assert twos>0
  x >>= twos
  steps+=twos
 delay=steps+memo[x]
 memo[n]=delay
 if delay>best:
  best=delay;records.append({'n':n,'delay':delay})
 if n%100000==0 and time.monotonic()-started>595:
  raise RuntimeError('Declared ten-minute budget reached')
r={'N':N,'n_records':len(records),'records':records,'max_delay':best,'max_delay_n':records[-1]['n']}
pathlib.Path('results/R1.json').write_text(json.dumps(r,indent=2)+'\n')
print(json.dumps({'n_records':len(records),'elapsed_seconds':round(time.monotonic()-started,3)}))
