| 1 | #!/bin/bashscip-shell filesystem . . `/bin/bash`. |
| 2 | # collatz.sh |
| 3 | |
| 4 | # The notorious "hailstone" or Collatz series. |
| 5 | # ------------------------------------------- |
| 6 | # 1) Get the integer "seed" from the command-line. |
| 7 | # 2) NUMBER <-- seed |
| 8 | # 3) Print NUMBER. |
| 9 | # 4) If NUMBER is even, divide by 2, or |
| 10 | # 5)+ if odd, multiply by 3 and add 1. |
| 11 | # 6) NUMBER <-- result |
| 12 | # 7) Loop back to step 3 (for specified number of iterations). |
| 13 | # |
| 14 | # The theory is that every such sequence, |
| 15 | #+ no matter how large the initial value, |
| 16 | #+ eventually settles down to repeating "4,2,1..." cycles, |
| 17 | #+ even after fluctuating through a wide range of values. |
| 18 | # |
| 19 | # This is an instance of an "iterate," |
| 20 | #+ an operation that feeds its output back into its input. |
| 21 | # Sometimes the result is a "chaotic" series. |
| 22 | |
| 23 | |
| 24 | MAX_ITERATIONS=200 |
| 25 | # For large seed numbers (>32000), try increasing MAX_ITERATIONS. |
| 26 | |
| 27 | h=${1:-$$} # Seed. |
| 28 | # Use $PID as seed, |
| 29 | #+ if not specified as command-line arg. |
| 30 | |
| 31 | echoscip-shell system . . echo. |
| 32 | echoscip-shell system . . echo. "C($h) -*- $MAX_ITERATIONS Iterations" |
| 33 | echoscip-shell system . . echo. |
| 34 | |
| 35 | for ((i=1; i<=MAX_ITERATIONS; i++)) |
| 36 | do |
| 37 | |
| 38 | # echo -n "$h " |
| 39 | # ^^^ |
| 40 | # tab |
| 41 | # printf does it better ... |
| 42 | COLWIDTH=%7d |
| 43 | printf $COLWIDTH $h |
| 44 | |
| 45 | let "remainder = h % 2" |
| 46 | if [ "$remainder" -eq 0 ] # Even? |
| 47 | then |
| 48 | let "h /= 2" # Divide by 2. |
| 49 | else |
| 50 | let "h = h*3 + 1" # Multiply by 3 and add 1. |
| 51 | fi |
| 52 | |
| 53 | |
| 54 | COLUMNS=10 # Output 10 values per line. |
| 55 | let "line_break = i % $COLUMNS" |
| 56 | if [ "$line_break" -eq 0 ] |
| 57 | then |
| 58 | echo |
| 59 | fi |
| 60 | |
| 61 | done |
| 62 | |
| 63 | echoscip-shell system . . echo. |
| 64 | |
| 65 | # For more information on this strange mathematical function, |
| 66 | #+ see _Computers, Pattern, Chaos, and Beauty_, by Pickover, p. 185 ff., |
| 67 | #+ as listed in the bibliography. |
| 68 | |
| 69 | exit 0 |