I have some values which I need to put in a row-major form, i.e. fill the column of a tabular on the basis of its width, as described in the MWE.
\documentclass[a4paper]{article}
\usepackage[margin=2cm]{geometry} % Just for this example
\setlength{\tabcolsep}{0.5cm}
\newcommand\myelement{\rule{1cm}{0.5cm}}
\begin{document}
Suppose each element width is 1 cm.
The whole page is 21 cm - 2*2 cm = 19 cm and therefore can contain
(19 cm / (1 cm + 2*0.5 cm)) = 9.5 = 9 elements, so the output should be like:
\begin{tabular}{rrrrrrrrr}
\myelement & \myelement & \myelement & \myelement & \myelement & \myelement & \myelement & \myelement & \myelement\\
\myelement & \myelement & \myelement & \myelement & \myelement & \myelement & \myelement & \myelement & \myelement\\
\myelement & \myelement & \myelement
\end{tabular}
~\\[1cm]
\begin{minipage}{0.5\linewidth}
Here the output should be like:
\begin{tabular}{rrrr}
\myelement & \myelement & \myelement & \myelement \\
\myelement & \myelement & \myelement & \myelement \\
\myelement & \myelement & \myelement & \myelement \\
\myelement & \myelement & \myelement & \myelement \\
\myelement & \myelement & \myelement & \myelement \\
\myelement
\end{tabular}
\end{minipage}
\end{document}
The number of columns must be deduced automatically from the width of the box which contains the "autocolumn environment/command" (name that as you want), provided the maximum width of the elements.
Any idea? I could use LuaLaTeX, but this solution would be too slow and memory hungry, so this is the last option.