how to do nested loops of variable depth? Addendum

Stephan Rudlof sr at evolgo.de
Wed Dec 19 18:42:52 UTC 2001


Boris_Gaertner at msg.de wrote:
> 
>    Part 1.1    Type: Plain Text (text/plain)
>            Encoding: quoted-printable

So it is appearing in my mail program...

But the code snippet in it (see below) is really a nice CSOTD...

Greetings,

Stephan


-------------------------
Hallo Hans,

nice to hear that your problem is solved.

I rechecked my proposal and I think that I did a lot of
unnecessary assignments. Every time I saw that I reached
maximal recursion depth, I celebrated that event in a loop
that assigned values to all elements of the tuple. That is
overdoing: Every call of the method 
result:tupel:idx:allStreams: has the responsibility
to assign to exactly one index position of the tuple to
be constructed. Here is a revised version of that method
that emphasizes that responsibility and avoids unneeded
assignments. The gain in time is possibly not substantial,
but the gain in clarity is.

result: r tupel: tupel idx: myIdx allStreams: allStreams

   "  this method is recursive. Recursion runs from values 1 to allStreams 
size  of parameter myIdx. Each call of that method has the responsiblity 
to provide all possible values for one index position of the result 
tuples. That index position is given by the value of  myIdx."

 [tupel at: myIdx put: (allStreams at: myIdx) peek.
  myIdx = allStreams size
          ifTrue: [r addLast: tupel shallowCopy]
         ifFalse:  [self  result: r tupel: tupel idx: myIdx + 1 
allStreams: allStreams].
        (allStreams at: myIdx)
          next; 
             atEnd
 ] 
 whileFalse: [].
 (allStreams at: myIdx) reset.
 ^r


Cheers again
Boris Gärtner


mailto: Boris_Gaertner at msg.de
-------------------------

-- 
Stephan Rudlof (sr at evolgo.de)
   "Genius doesn't work on an assembly line basis.
    You can't simply say, 'Today I will be brilliant.'"
    -- Kirk, "The Ultimate Computer", stardate 4731.3




More information about the Squeak-dev mailing list