collatz0.html
001| '''Calculator for the Collatz Conjecture.
001|
001| The algorithm starts with a number, N, and:
001|
001| > if N is even; divide it by 2 {n = n/2}
001| > if N is odd; multiply it by 3 and add 1 {n = 3n+1}
001|
001| Repeat until N becomes 1. (Which it supposely always will.)
001|
001| Note that there is a "backbone" of sorts consisting of the
001| binary numbers (1,2,4,8,..) that quickly reduces to 1, so
001| any N that hits this backbone is guaranteed to reach 1.
001|
001|
001| | 1|
001| | 2|
001| | 4|
001| | 8|
001| | 16>------------------->++++|
001| | 32| | 5|
001| | 64>-------------->++++| 10>--------->++++|
001| | 128| | 21| 20| | 3|
001| | 256>---->++++| | 42| 40| | 6|
001| | 512| | 85| | 84| 80| | 12|
001| |1024>++++| 170| | 168| 160>---->++++| 24|
001| |2048| 341| 340>++++| 336| 320| | 53| 48|
001| |4096| 672| 680| 113| 672| 640>++++| 106| 96|
001| |8192|1344|1360| 226|1344|1280| 213| 212| 192|
001|
001|
001| |*|
001| |*|
001| |*|
001| |*|
001| |*>------->_
001| |*| |*|
001| |*>----->_|*>--->_
001| |*| |*|*| |*|
001| |*>->_ |*|*| |*|
001| |*| |*| |*|*| |*|
001| |*>_|*| |*|*>->_|*|
001| |*|*|*>_|*|*| |*|*|
001| |*|*|*|*|*|*>_|*|*|
001| |*|*|*|*|*|*|*|*|*|
001|
001|
001| |
001| |
001| |
001| |
001| +----+
001| | |
001| +---++--+
001| | || |
001| +-+ || |
001| | | || |
001| ++| |+-+|
001| ||++|| ||
001| |||||++||
001| |||||||||
001| '''
002|
003| from sys import argv, stdout
004| from os import path
005|
006| BasePath = r'C:\CJS\prj\Python\app\maths'
007| OutputFilename = path.join(BasePath,'out','collatz.out')
008| Output = stdout
009|
010| collatz = lambda n: ((n*3)+1) if (n % 2) else (n//2)
011| plural = lambda n: '' if n==1 else 's'
012|
013|
014| def calc_collatz_path (n):
015| steps = [n]
016| while 1 < n:
017| nn = collatz(n)
018| n = nn
019| steps.append(nn)
020| return steps
021|
022|
023|
024| class CollatzNode (object):
025| def __init__ (self, n, up=None, dn=None):
026| self.n = n
027| self.up = up
028| self.dn = dn
029|
030| def __str__ (self):
031| u = str(self.up) if self.up else '-'
032| d = str(self.dn) if self.dn else '-'
033| return '[%5d] (%s) (%s)' % (self.n, u, d)
034|
035|
036| def build_collatz_tree (*args):
037| '''Build Collatz Tree.
037|
037| Creates and returns a dictionary of numeric values.
037| Each value has a list of values it links to, which
037| are the next Collatz values *UP* the chain.
037| '''
038| emsg = "Steps don't match: %d != %d"
039| tree = {1:CollatzNode(1,up=2)}
040| for a in args:
041| n = int(a)
042| steps = list(reversed(calc_collatz_path(n)))
043|
044| for ix in range(len(steps)-1):
045| step,next_step = steps[ix:ix+2]
046|
047| if step not in tree:
048| tree[step] = CollatzNode(step)
049|
050| node = tree[step]
051| if next_step < step:
052|
053| if node.dn:
054| assert (node.dn == next_step), ("Steps don't match: %d != %d" % (next_step, node.dn))
055| else:
056| node.dn = next_step
057| else:
058|
059| if node.up:
060| assert (node.up == next_step), ("Steps don't match: %d != %d" % (next_step, node.up))
061| else:
062| node.up = next_step
063|
064|
065| last_step = steps[-1]
066| if last_step not in tree:
067| tree[last_step] = CollatzNode(last_step)
068| return tree
069|
070|
071| def travel_collatz_tree (tree, cb_ftn=None):
072| k = min(tree.keys())
073| print('Travel Collatz Tree', file=Output)
074| print('First key: %d' % k, file=Output)
075| _travel_collatz_tree (k, tree, cb_ftn)
076| return k
077|
078| def _travel_collatz_tree (k, tree, cb_ftn=None):
079| node = tree[k]
080| u = ('%5d' % node.up) if node.up else '-----'
081| d = ('%5d' % node.dn) if node.dn else '-----'
082| b = ' ->' if (node.up and node.dn) else ''
083| e = '' if (node.up or node.dn) else '\n'
084| print('%5d: (%s) (%s)%s%s' % (node.n,u,d,b,e), file=Output)
085| if node.up:
086| _travel_collatz_tree(node.up, tree, cb_ftn)
087| if node.dn:
088| _travel_collatz_tree(node.dn, tree, cb_ftn)
089|
090|
091|
092| def generate_collatz_bush (n, level=0, depth=12):
093| if (n < 1) or (depth < level):
094| return None
095|
096| u = generate_collatz_bush(2*n, level+1, depth)
097|
098| m = n - 1
099| d = None if m % 3 else generate_collatz_bush(m//3, level+1, depth)
100| if d and (((d[0] % 2) == 0) or (d[0] == 1)):
101| d = None
102|
103| return (n, u, d)
104|
105|
106| def travel_collatz_bush (bush):
107| print('Travel Collatz Bush', file=Output)
108| _travel_collatz_bush(bush)
109| print(file=Output)
110|
111| def _travel_collatz_bush (node):
112| n = node[0]
113| u = ('%5d' % node[1][0]) if node[1] else '-----'
114| d = ('%5d' % node[2][0]) if node[2] else '-----'
115| b = ' ->' if (node[1] and node[2]) else ''
116| e = '' if (node[1] or node[2]) else '\n'
117| print('%5d: (%5s) (%5s)%s%s' % (n,u,d,b,e), file=Output)
118| if node[1]:
119| _travel_collatz_bush(node[1])
120| if node[2]:
121| _travel_collatz_bush(node[2])
122|
123|
124| def do_scan (*args):
125| print('scan: %d args' % len(args), file=Output)
126| a1 = int(args[0]) if 0 < len(args) else 2
127| a2 = int(args[1]) if 1 < len(args) else 32
128| a3 = int(args[2]) if 2 < len(args) else 1
129|
130| max_steps, max_n = 0,0
131| high_step, high_n = 0,0
132| print('===', file=Output)
133| for n in range(a1, a2+1, a3):
134| steps = calc_collatz_path(n)
135| ns = len(steps)
136| hs = max(steps)
137| print('[%4d] %4d step%s (highest step: %5d)' % (n, ns, plural(ns), hs), file=Output)
138| if max_steps < ns:
139| max_steps = ns
140| max_n = n
141| if high_step < hs:
142| high_step = hs
143| high_n = n
144| print('===', file=Output)
145| print('>>> Maximum steps: %4d (from: %4d)' % (max_steps, max_n), file=Output)
146| print('>>> Highest step: %5d (from: %4d)' % (high_step, high_n), file=Output)
147| print('===', file=Output)
148| return 'Done'
149|
150| def do_tree (*args):
151| print('tree: %d args' % len(args), file=Output)
152| a1 = int(args[0]) if 0 < len(args) else 3
153| a2 = int(args[1]) if 1 < len(args) else 64
154| a3 = int(args[2]) if 2 < len(args) else 1
155|
156| numbers = list(range(a1, a2+1, a3))
157|
158|
159| tree = build_collatz_tree(*numbers)
160| travel_collatz_tree(tree)
161|
162|
163| return 'Done'
164|
165| def do_main (*args):
166| print('main: %d args' % len(args), file=Output)
167| for a in args:
168| n = int(a)
169| print('Collatz Path for: %d' % n, file=Output)
170| steps = calc_collatz_path(n)
171| ns = len(steps)
172| print('>> %d step%s; highest step: %d' % (ns, plural(ns), max(steps)), file=Output)
173| print('>> %s' % str(steps), file=Output)
174| print(file=Output)
175| return 'Done'
176|
177| def do_test (*args):
178| print('test: %d args' % len(args), file=Output)
179| a1 = int(args[0]) if 0 < len(args) else 1
180| a2 = int(args[1]) if 1 < len(args) else 16
181| a3 = int(args[2]) if 2 < len(args) else 1
182|
183| bush = generate_collatz_bush(a1, depth=a2)
184| travel_collatz_bush(bush)
185| return 'Done'
186|
187| def dispatch (cmd, *args):
188| print('command: %s' % cmd, file=Output)
189| print('arguments: %d' % len(args), file=Output)
190| print(file=Output)
191| if cmd == 'tree': return do_tree(*args)
192| if cmd == 'scan': return do_scan(*args)
193| if cmd == 'main': return do_main(*args)
194| if cmd == 'test': return do_test(*args)
195| return 'Nothing to do!'
196|
197| if __name__ == '__main__':
198| print('autorun: %s' % argv[0])
199| cmd = argv[1] if 1 < len(argv) else 'test'
200| etc = argv[2:] if 2 < len(argv) else [1, 25]
201| Output = open(OutputFilename, mode='w', encoding='utf-8')
202| try:
203| obj = dispatch(cmd, *etc)
204| print(file=Output)
205| print(obj, file=Output)
206| except:
207| raise
208| finally:
209| Output.close()
210|
211| '''eof'''
212|