
# collatz.py
# Andrew Davison, ad@coe.psu.ac.th, May 2025
'''
  Generate a single graph showing how all the numbers
  between 1 and n are changed by the Collatz conjecture.

 https://en.wikipedia.org/wiki/Collatz_conjecture
'''

import graphviz

TEMP_FNM = 'temp_graph'

def collatz(num, g):
  prev = num; curr = num
  while num != 1:
    prev = num 
    if num%2 == 0:
      num = num//2
    else:
      num = 3*num + 1
    curr = num

    # only add new edges to g
    edge = (prev, curr)  
    if not edge in edges:
      g.edge(str(prev), str(curr))
      edges.append(edge)


n = int(input("Max n (e.g. 15)? "))

g = graphviz.Graph(format='png')
g.attr(rankdir='LR')
g.attr(label='Collatz(): 1 to '+str(n))

edges = []  # global for all generated edges
for i in range(1, n+1):
  collatz(i, g)

g.render(filename=TEMP_FNM, view=True, cleanup=True)
