how to do nested loops of variable depth?

goran.hultgren at bluefish.se goran.hultgren at bluefish.se
Wed Dec 19 10:21:34 UTC 2001


Hi!

"Baveco,  Hans" <J.M.Baveco at Alterra.wag-ur.nl> wrote:
> when I have the simple case of 2 arrays and I want to combine each value of
> the first with each value of the second, I know what to do.
> Something like 
> 	result := OrderedCollection new: (array1 size * array2 size).
> 	1 to: array1 size do: [:i | 1 to: array2 size do: [:j | result
> addLast: (Array with: (array1 at: i) with: (array2 at: j))].
> will do the trick.
> Of course this can be extended to any required depth of nesting (=number of
> input arrays).
> However, what would be the smalltalk way to handle a variable number of
> input arrays (=variable depth of nesting)? I guess there must be some smart
> (recursive) way to deal with this problem in smalltalk/squeak. 
> Can anyone set me on the right track?
> hans

Well, I am not sure about the "Smalltalk way" :-) but here is a method
example (if I have understood you correct):
<CSOTD>
transpose: columns
"Assume that <columns> is an Array of Arrays having the same size each
representing a column in a matrix.
Return a new 'transposed' Array of Arrays where each array represents a
row of the matrix."

| rows |
rows _ Array new: columns first size.
1 to: rows size do: [:n | rows at: n put: (columns collect: [:column |
column at: n])].
^rows
</CSOTD>

Ok, making this code Collection-type-independent handling
SequencableCollections with subclasses
(including dynamically resizable ones and Array which is not) is left as
an exercise! :-)

regards, Göran




More information about the Squeak-dev mailing list