how to do nested loops of variable depth?

Chris Muller afunkyobject at yahoo.com
Thu Dec 20 05:46:46 UTC 2001


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