Search code examples
collectionssmalltalktransposepharo

Is there a Smalltalk way to transposing an Array?


Suppose I have an array which looks like this

{ { #a . #b . #c } . 
  { #e . #f . #g } }.

Is there a quick way to turn this into

 { { #a . #e } . { #b . #f } . { #c . #g } }

the code should work for n-element subarrays too.

{ { #a . #b . #c . #d } . 
  { #e . #f . #g . #h } }.

Solution

  • General purpose one liner, no assumptions about column or row count.

    (1 to: rows first size) collect: [:column | rows collect: [:row | row at: column]]
    

    Some Smalltalk's even implement:

    SequenceableCollection>>keys
        ^1 to: self size
    

    In that case the first can be even nicer implemented as:

     rows first keys collect: [:column | rows collect: [:row | row at: column]]