27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

# Q(1) = Q(2) = 1<br />

# Q(n) = Q(n − Q(n−1)) + Q(n − Q(n−2)), for n>2<br />

# This is a "chaotic" integer series with strange and unpredictable behavior.<br />

# The first 20 terms of the series are:<br />

# 1 1 2 3 3 4 5 5 6 6 6 8 8 8 10 9 10 11 11 12<br />

# See Hofstadter's book, "Goedel, Escher, Bach: An Eternal Golden Braid",<br />

# p. 137, ff.<br />

LIMIT=100 # Number of terms to calculate<br />

LINEWIDTH=20 # Number of terms printed per line<br />

Q[1]=1 # First two terms of series are 1.<br />

Q[2]=1<br />

echo<br />

echo "Q−series [$LIMIT terms]:"<br />

echo −n "${Q[1]} "<br />

# Output first two terms.<br />

echo −n "${Q[2]} "<br />

for ((n=3; n 2<br />

# Need to break the expression into intermediate terms,<br />

# since Bash doesn't handle complex array arithmetic very well.<br />

let "n1 = $n − 1"<br />

let "n2 = $n − 2"<br />

# n−1<br />

# n−2<br />

t0=`expr $n − ${Q[n1]}` # n − Q[n−1]<br />

t1=`expr $n − ${Q[n2]}` # n − Q[n−2]<br />

T0=${Q[t0]}<br />

T1=${Q[t1]}<br />

Q[n]=`expr $T0 + $T1`<br />

echo −n "${Q[n]} "<br />

# Q[n − Q[n−1]]<br />

# Q[n − Q[n−2]]<br />

# Q[n − Q[n−1]] + Q[n − ![n−2]]<br />

if [ `expr $n % $LINEWIDTH` −eq 0 ] # Format output.<br />

then # mod<br />

echo # Break lines into neat chunks.<br />

fi<br />

done<br />

echo<br />

exit 0<br />

# This is an iterative implementation of the Q−series.<br />

# The more intuitive recursive implementation is left as an exercise.<br />

# Warning: calculating this series recursively takes a *very* long time.<br />

−−<br />

Bash supports only one−dimensional arrays, however a little trickery permits simulating multi−dimensional<br />

ones.<br />

Chapter 26. Arrays 306

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!