Carpet fishing (sh)

From LiteratePrograms

Jump to: navigation, search

Contents

theory

There is not much to an implementation of Dilbert's carpet fishing game; it is simply a loop of indefinitely iterated actions — Lather. Rinse. Repeat.

NB. $RANDOM produces a new pseudorandom value each time it is evaluated.

practice

Our actions are only slightly more involved than Lather and Rinse.

First we delay for a random time:

<<process fish>>=
sleep $((TIME*(30 + $RANDOM % 60)))

then we pick a random species:

<<process fish>>=
species=$(echo $fish | awk '{print $(1+('$RANDOM' % NF))}')

and report a niible in a random location:

<<normal nibble>>=
echo $species nibbling in area $(($RANDOM % $grid))

a complication

At the risk of nearly doubling the code size, we can add the "salmon run" feature. During a run, fish appear in several random grid locations. As we do not keep state, we are choosing elements with replacement, and piping through sort and uniq allow us to remove any duplicates.

<<salmon run>>=
echo $species running in areas: $(
                    for i in 0 1 2 3 4 5 6; do
               echo $(($RANDOM % $grid))
                    done | sort -n | uniq)

This code will be activated if "salmon" is the chosen species.

<<process fish>>=
if [ X$species != Xsalmon ]; then
                    normal nibble
else
                    salmon run
fi

wrapping up

Finally, we provide an overridable default configuration, and wrap the fish processing code up in an infinite loop.

<<carpetfish.sh>>=
fish=${FISH:-"salmon trout catfish bass sturgeon crappie shad"} # species
time=${TIME:-60}                                                # time quantum
grid=${GRID:-36}                                                # grid size

while true; do
                    process fish
done

Over the course of a day, this will produce output something along the lines of

crappie nibbling in area 33
trout nibbling in area 29
bass nibbling in area 28
crappie nibbling in area 23
trout nibbling in area 10
salmon running in areas: 0 5 14 15 19 21
trout nibbling in area 24
catfish nibbling in area 2
Views
Personal tools
Navigation