| 1 | #!/bin/bash |
| 2 | |
| 3 | # Douglas Hofstadter's notorious "Q-series": |
| 4 | |
| 5 | # Q(1) = Q(2) = 1 |
| 6 | # Q(n) = Q(n - Q(n-1)) + Q(n - Q(n-2)), for n>2 |
| 7 | |
| 8 | # This is a "chaotic" integer series with strange |
| 9 | #+ and unpredictable behavior. |
| 10 | # The first 20 terms of the series are: |
| 11 | # 1 1 2 3 3 4 5 5 6 6 6 8 8 8 10 9 10 11 11 12 |
| 12 | |
| 13 | # See Hofstadter's book, _Goedel, Escher, Bach: An Eternal Golden Braid_, |
| 14 | #+ p. 137, ff. |
| 15 | |
| 16 | |
| 17 | LIMIT=100 # Number of terms to calculate. |
| 18 | LINEWIDTH=20 # Number of terms printed per line. |
| 19 | |
| 20 | Q[1]=1 # First two terms of series are 1. |
| 21 | Q[2]=1 |
| 22 | |
| 23 | echo |
| 24 | echo "Q-series [$LIMIT terms]:" |
| 25 | echo -n "${Q[1]} " # Output first two terms. |
| 26 | echo -n "${Q[2]} " |
| 27 | |
| 28 | for ((n=3; n <= $LIMIT; n++)) # C-like loop expression. |
| 29 | do # Q[n] = Q[n - Q[n-1]] + Q[n - Q[n-2]] for n>2 |
| 30 | # Need to break the expression into intermediate terms, |
| 31 | #+ since Bash doesn't handle complex array arithmetic very well. |
| 32 | |
| 33 | let "n1 = $n - 1" # n-1 |
| 34 | let "n2 = $n - 2" # n-2 |
| 35 | |
| 36 | t0=`expr $n - ${Q[n1]}` # n - Q[n-1] |
| 37 | t1=`expr $n - ${Q[n2]}` # n - Q[n-2] |
| 38 | |
| 39 | T0=${Q[t0]} # Q[n - Q[n-1]] |
| 40 | T1=${Q[t1]} # Q[n - Q[n-2]] |
| 41 | |
| 42 | Q[n]=`expr $T0 + $T1` # Q[n - Q[n-1]] + Q[n - Q[n-2]] |
| 43 | echo -n "${Q[n]} " |
| 44 | |
| 45 | if [ `expr $n % $LINEWIDTH` -eq 0 ] # Format output. |
| 46 | then # ^ modulo |
| 47 | echo # Break lines into neat chunks. |
| 48 | fi |
| 49 | |
| 50 | done |
| 51 | |
| 52 | echo |
| 53 | |
| 54 | exit 0 |
| 55 | |
| 56 | # This is an iterative implementation of the Q-series. |
| 57 | # The more intuitive recursive implementation is left as an exercise. |
| 58 | # Warning: calculating this series recursively takes a VERY long time |
| 59 | #+ via a script. C/C++ would be orders of magnitude faster. |