6
$\begingroup$

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
$\endgroup$

3 Answers 3

3
$\begingroup$

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]]]  
$\endgroup$
10
$\begingroup$
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
$\endgroup$
2
  • 2
    $\begingroup$ 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 mathematica.stackexchange.com/questions/119/… $\endgroup$ Nov 27, 2022 at 14:08
  • $\begingroup$ @Syed thank you. the second part works beautifully. :) $\endgroup$ Nov 27, 2022 at 20:09
3
$\begingroup$

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

$\endgroup$
2
  • $\begingroup$ How could be this modified so that it partitions (order down columns) based on number of columns desired? For example getGrid[list_, columns_]:=... $\endgroup$ Nov 29, 2022 at 11:39
  • 1
    $\begingroup$ Use: getGrid[list, Ceiling[Length[list]/columns]] $\endgroup$ Nov 29, 2022 at 11:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.