This simple example merely lists all possible outcomes of rolling 4,
6, 8, 10, 12, and 20 sided dice at once. A super-for loop requires an
array to specify the loop indices... here we have 6 dice and the
number of sides determines the indices. The code is easily modified
for an arbitrary number of dice (which is the whole point).
I identify three parts of a super-for which I called the prologue,
body, and epilog. Under most circumstances, I think the main body only
would get used.
I invite you to show off your AWK skills by improving the code if I
made any silly choices.
Cheers,
Jason
#shows an example of a superfor loop
BEGIN {
#define loop maximums
loopmax[1]=4
loopmax[2]=6
loopmax[3]=8
loopmax[4]=10
loopmax[5]=12
loopmax[6]=20
#call the loop
superfor(6)
}
#call the function as superfor(loopdepth). the zz is a local variable.
function superfor(loopdepth, zz) {
currloopnum++
#start of prologue
#end of prologue
for(loopcounter[currloopnum]=1; loopcounter[currloopnum]<=loopmax
[currloopnum]; loopcounter[currloopnum]++) {
if ( loopdepth==1 ) {
#start of superfor body
for (zz=1;zz<=currloopnum;zz++) {
printf loopcounter[zz] FS
}
print ""
#end of superfor body
}
else if ( loopdepth>1 )
superfor(loopdepth-1)
}
#start of epilog
#end of epilog
loopdepth++ ; currloopnum--
}
Well, a bit long-winded, maybe; certainly no silly choices you made.
But I suppose your algorithm will get slightly better comprehensible
if you make 'currloopnum' a parameter of the recursive function call.
(Using shorter names in this specific case of a small function might
make it easier to overview the operation done. YMMV.) And the split
is just another minor goodie added. It's basically your program that
you see below, I haven't changed much of the core of your algorithm.
BEGIN { n = split ("4 6 8 10 12 20", upb) ; multifor(n, 1) }
function multifor (depth, lno, nn)
{
for (lc[lno]=1; lc[lno]<=upb[lno]; lc[lno]++)
{
if (depth > 1)
multifor(depth-1, lno+1)
else
{
for (nn=1; nn<=lno; nn++)
printf("%s", lc[nn] FS)
print ""
}
}
}
Janis
Great. It's always interesting to see how others would have done
something.
Jason
I think this would make a great application for indirect function calls:
function superfor(loopdepth, prologue, body, epilogue, zz)
{
currloopnum++
@prologue()
for(loopcounter[currloopnum]=1; loopcounter[currloopnum]<=loopmax [currloopnum]; loopcounter[currloopnum]++) {
if ( loopdepth==1 ) {
@body()
}
else if ( loopdepth>1 )
superfor(loopdepth-1)
}
@epilogue()
loopdepth++ ; currloopnum--
}
--
Aharon (Arnold) Robbins arnold AT skeeve DOT com
P.O. Box 354 Home Phone: +972 8 979-0381
Nof Ayalon Cell Phone: +972 50 729-7545
D.N. Shimshon 99785 ISRAEL