how to do nested loops of variable depth?

Baveco, Hans J.M.Baveco at Alterra.wag-ur.nl
Thu Dec 20 11:30:26 UTC 2001


Thanks Chris, two questions though, would this work in squeak (you use local
block variables)? and would it be possible to create blocks with a specified
number of expected arguments automatically? (otherwise we still need to code
all these blocks expecting different nr of arguments onbeforehand).

Hans


I see you already have a solution.  Here is mine that
does not use any recursion, minimizes allocation and,
like Boris', values each combination as-you-go.  This
one will work in a workspace.  Just supply the doBlock
with the correct number of arguments and away you go!

	| anArrayOfArrays doBlock numberOfCombinations args |
	anArrayOfArrays _ OrderedCollection new
		add: #('eat' 'wear');
		add: #('green' 'blue' 'orange');
		add: #('apples' 'oranges' 'cherries');
		yourself.
	doBlock _
		[ :eachVerb :eachColor :eachFruit | Transcript cr;
show: eachVerb, eachColor, eachFruit ].
	numberOfCombinations :=
		anArrayOfArrays
			inject: 1
			into: [ :prod :each | each size * prod ].
	args := Array new: anArrayOfArrays size.
	1
		to: numberOfCombinations
		do:
			[ :elementIndex |
			1
				to: anArrayOfArrays size
				do:
					[ :innerIndex | | eachInnerArray
radix |
					eachInnerArray := anArrayOfArrays
at: innerIndex.
					radix := 1.
					1
						to: innerIndex - 1
						do: [ :eachOrder | radix :=
radix *
(anArrayOfArrays at: eachOrder) size ].
					args
						at: innerIndex
						put: (eachInnerArray at:
(elementIndex // radix
\\ eachInnerArray size + 1)) ].
			doBlock valueWithArguments: args ]




__________________________________________________
Do You Yahoo!?
Check out Yahoo! Shopping and Yahoo! Auctions for all of
your unique holiday gifts! Buy at http://shopping.yahoo.com
or bid at http://auctions.yahoo.com





More information about the Squeak-dev mailing list