表形式の環境でのループ

表形式の環境でのループ

サイズに応じて自動的にテーブルを作成しようとしています。LaTeX にはループ コマンドが多数存在するため、どれが適切かを判断するのが困難です。プレーン TeX ループとパッケージのループを試しましたがforlooppgfloop成功しませんでした。

どうやら、環境内でループを実行すると問題が発生しますtabular。また、最初にループを実行し、出力文字列を に保存してtokenから、 内にトークンを印刷することも試みましたtabular。これは、いくつかのケースでは機能します。

以下に最小限の例を示します。まず、私が作成したいものは次のとおりです。

\begin{tabular}{|*{4}{c|}}
  1&2&3&4
\end{tabular}

ここで、TeX ループで試したことは次のとおりです。

\newcounter{numofcol}\setcounter{numofcol}{4}
\newcounter{tmpcol}\setcounter{tmpcol}{1}

\begin{tabular}{|*{\thenumofcol}{c|}}
  \thetmpcol
  \loop
    \ifnum\value{tmpcol}<\value{numofcol}%
    \stepcounter{tmpcol}%
    &\thetmpcol
  \repeat
\end{tabular}

どうやら、&シンボルはループ内で問題を引き起こしているようです。パッケージforloopまたはのループを使用した場合も同じことが起こりますpgfloop。エラーは次のようになります。

ERROR: Forbidden control sequence found while scanning use of \loop.

--- TeX said ---
<inserted text> 
                \par 
l.140     &
           \thetmpcol
--- HELP ---
No help available

tokenそこで、行の文字列を次のように保存できると考えました。

\newcounter{numofcol}\setcounter{numofcol}{4}
\newcounter{tmpcol}\setcounter{tmpcol}{1}
\newtoks\tmprowcontent

\tmprowcontent={x}
\loop%
\ifnum\value{tmpcol}<\value{numofcol}%
  \stepcounter{tmpcol}%
  \tmprowcontent=\expandafter{\the\expandafter\tmprowcontent & x}%
\repeat

\begin{tabular}{|*{\thenumofcol}{c|}}
  \the\tmprowcontent
\end{tabular}

これは、そのカウンターを に含めない場合に機能します。現在のカウンター値にtoken置き換えると、つまり、x

\newcounter{numofcol}\setcounter{numofcol}{4}
\newcounter{tmpcol}\setcounter{tmpcol}{1}
\newtoks\tmprowcontent

\tmprowcontent={\thetmpcol}
\loop%
\ifnum\value{tmpcol}<\value{numofcol}%
  \stepcounter{tmpcol}%
  \tmprowcontent=\expandafter{\the\tmprowcontent & \thetmpcol}%
\repeat

\begin{tabular}{|*{\thenumofcol}{c|}}
  \the\tmprowcontent
\end{tabular}

すると、各エントリはカウンタの最後の値、4つまり になります。これは を使用しているためです\expandafter。ただし、 を使用しないと\expandafter、TeX はメモリ不足を通知します。

したがって、私の質問は、どうすればこれを機能させることができるかということです。

答え1

値を単純に反復処理できますが、&あまり早く表示されてテストの途中でテーブル セルが終了しないように、値を非表示にする必要がある場合もあります。

ここに画像の説明を入力してください

\documentclass{article}

\begin{document}

\newcounter{numofcol}\setcounter{numofcol}{4}
\newcounter{tmpcol}\setcounter{tmpcol}{0}

\newcommand\foo{%
  \stepcounter{tmpcol}%
  \thetmpcol
  \ifnum\value{tmpcol}<\value{numofcol}\hiddenamp\expandafter\foo\fi}
\newcommand\hiddenamp{&}

\begin{tabular}{|*{\thenumofcol}{c|}}
  \foo
\end{tabular}
\end{document}

関連情報