在具有可变列数的表格(或类似表格)中自动换行(而不是换行)

在具有可变列数的表格(或类似表格)中自动换行(而不是换行)

我有一些值需要以行主格式输入,即根据表格的宽度填充表格的列,如 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}

必须根据包含“自动列环境/命令”(根据需要命名)的框的宽度自动推断出列数,并提供元素的最大宽度。

有什么想法吗?我可以使用 LuaLaTeX,但这种解决方案太慢而且占用大量内存,所以这是最后的选择。

答案1

在此处输入图片描述

\documentclass[a4paper]{article}
\usepackage[margin=2cm]{geometry} % Just for this example
\setlength{\tabcolsep}{0.5cm}
\newcommand\myelement{\rule{1cm}{0.5cm}}
\newcommand\xelement{\makebox[2cm]{\myelement}\hspace{0pt}}

\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{flushleft}
\xelement  \xelement  \xelement  \xelement  \xelement  \xelement  \xelement  \xelement  \xelement
\xelement  \xelement  \xelement  \xelement  \xelement  \xelement  \xelement  \xelement  \xelement
\xelement  \xelement  \xelement
\end{flushleft}

\bigskip

\begin{minipage}{0.5\linewidth}
Here the output should be like:

\begin{flushleft}
\xelement  \xelement  \xelement  \xelement 
\xelement  \xelement  \xelement  \xelement 
\xelement  \xelement  \xelement  \xelement 
\xelement  \xelement  \xelement  \xelement 
\xelement  \xelement  \xelement  \xelement 
\xelement
\end{flushleft}
\end{minipage}
\end{document}

相关内容