6

Partitioning a List into sub-lists and placing them directly into a Grid orders sub-lists across rows. Is there an idiot-proof built-in function or a simple algorithm for ordering sub-lists down columns for an unknown number of list elements with an unknown end-user selected n of sub-list lengths?

This outputs ordered across rows:

list = Range[8]
n = 3
Grid[Partition[list, UpTo[n]]]

Out:

1  2  3
4  5  6
7  8

The goal is ordered down columns:

1  4  7
2  5  8
3  6
Jules Manson
  • 2,457
  • 11
  • 19

3 Answers3

10
Grid@Flatten[Partition[list, UpTo[n]], {{2}, {1}}]

$$\begin{array}{ccc} 1 & 4 & 7 \\ 2 & 5 & 8 \\ 3 & 6 & \text{} \\ \end{array}$$

Please see the docs for Flatten and browse for ragged under Applications.


OR

The Transpose operation requires a rectangular array, so one can use PadRight prior to it with the same result. Choose "x" to be something unikely to be found in the data.

Transpose@(PadRight[#, n, "x"] & /@ Partition[list, UpTo[n]]) /. 
  "x" -> Nothing // Grid
Syed
  • 52,495
  • 4
  • 30
  • 85
  • 2
    Nice I did know UpTo can be used like that. For the Partition[list, UpTo[n]] there is also a resource function NearEqualPartition. For OP: For using Flatten like a transposition for ragged lists see particularly the answer by WReach here https://mathematica.stackexchange.com/questions/119/flatten-command-matrix-as-second-argument – userrandrand Nov 27 '22 at 14:08
  • @Syed thank you. the second part works beautifully. :) – Jules Manson Nov 27 '22 at 20:09
3

I assume you want to partition a given list of length: m into sublists of length: n and arrange the sublists as column in a grid. This can be done by choosing every n-th element with an offset from 0..m/n:

  getGrid[list_, n_] := Module[{m = Length[list]},
  Grid[Table[
    If[(t = j + n i) >= m, Nothing, t + 1], {j, 0, n - 1}, {i, 0, m/n}]]
  ]

We may test this by:

list = Range[8];
getGrid[list, 2]

getGrid[list, 3]

enter image description here

getGrid[list, 4]

enter image description here

Daniel Huber
  • 51,463
  • 1
  • 23
  • 57
3

The response using a built-in function is that of Syed, no doubt. However, it is possible to build a list with the required permutations:

permutation =  Flatten[ Table[Range[i, Length[list], n], 
                       {i, 1, Ceiling[Length[list]/n]}] ];
Grid[Partition[Permute[list, permutation], UpTo[n]]]  
Vito Vanin
  • 568
  • 2
  • 8