我有一些值需要以行優先形式放入,即根據表格的寬度填充表格的列,如 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}