Solutions to the exercises from Monday, September 27, 2004 1. Here's a solution to Exercise 1. Notice that the basic structure of the script is pretty simple even though embedded commands (the commands enclosed in backquotes) are a bit hairy. % cat sorthat #!/bin/csh rm -f nums alphs bets touch nums alphs bets foreach word ( `cat $argv | tr "A-Z" "a-z" | tr -dc "a-z0-9 \n"` ) printf "." if ( `echo $word a | awk '{ print ( $1 < $2 ) }'` ) then echo $word >> nums else if ( `echo $word m | awk '{ print ( $1 < $2 ) }'` ) then echo $word >> alphs else echo $word >> bets endif end 2. Here's another solution to Exercise 1; this one uses a second script as a 'subroutine'. % cat stringlessthan #!/bin/csh echo $1 $2 | awk '{ print ( $1 < $2 ) }' % cat sorthat #!/bin/csh rm -f nums alphs bets touch nums alphs bets foreach word ( `cat $argv | tr "A-Z" "a-z" | tr -dc "a-z0-9 \n"` ) if ( `stringlessthan $word 'a'` ) then echo $word >> nums else if ( `stringlessthan $word 'm'` ) then echo $word >> alphs else echo $word >> bets endif end You might find it interesting to compare the running time of these two solutions. The 'time' utility provides timing information to benchmark commands: % time isprime 1987 1 0.450u 0.390s 0:01.18 71.1% 0+0k 0+10io 0pf+0w % time isprime 3 1 0.020u 0.140s 0:00.31 51.6% 0+0k 0+0io 0pf+0w You can learn about the timing summary using 'info time'. 2. A solution to Exercise 2: % cat diagonal #!/bin/csh set n = $argv[1] set i = 0 while ( $i < $n ) set j = 0 while ( $j < $n ) if ( $i == $j ) then printf "1 " else printf "0 " endif @ j ++ end printf "\n" @ i ++ end 3. Solution to Exercise 3: % cat isprime #!/bin/csh set n = $argv @ d = $n / 2 while ( $d > 1 ) @ r = $n % $d if ( $r == 0 ) then echo 0 exit endif @ d -- end echo 1 4. Solution to Exercise 4: % cat isprime #!/bin/csh set n = $argv @ d = $n / 2 while ( $d > 1 ) @ r = $n % $d if ( $r == 0 ) exit 1 @ d -- end exit 0