how to do nested loops of variable depth?
C. Gable Watts
CGableWatts at Mac.com
Thu Dec 20 18:16:23 UTC 2001
Whenever I hear about data being held and processed in arrays and arrays-of-arrays, it is often a sign that perhaps this is an opportunity for more abstract objects to be used to hold the data. It is likely you should consider making new classes that are a better abstraction for the information represented by the data in these arrays and arrays-of-arrays. But, assuming these collections of arrays are a good abstraction for your data, you could transpose them in the following way:
transposeArrays: anArrayOfArrays
"Transpose the given array of arrays. Answer a new array of arrays where the first sub-array holds all the first elements of the input arrays, the second sub-array holds all the second elements of the input arrays, and so on. All the input sub-arrays must be the same size and there must be at least one subarray."
resultArray := Array new: anArrayOfArrays first size.
1 to: result size do: [:elementNumber |
| resultSubArray |
resultSubArray := Array new: anArrayOfArrays size.
1 to: resultSubArray size do: [:i |
resultSubArray at: i put: ((anArrayOfArrays at: i) at: elementNumber)].
resultArray at: elementNumber put: resultSubArray].
^resultArray
>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?
More information about the Squeak-dev
mailing list
|