pgffor で内部リストの長さにアクセスする方法

pgffor で内部リストの長さにアクセスする方法

リストのリストがあり、ネストされた\foreachループを使用してそれらを反復処理しています。 を使用すると[count=\var]、 を使用して外側のループの長さにアクセスできます\var(反復処理した後)。ただし、このメソッドを使用して内側のループの長さにアクセスすることはできません。私の場合、すべての内側のループの長さは同じである必要がありますが、技術的には、最後の内側のループの長さにアクセスしたいと考えていました。これまでのところ、次のようになっています。

\documentclass{article}
\usepackage{tikz}
\begin{document}

% The first two work:

\begin{tikzpicture}
  \foreach \from [count=\to] in {2,3,1} {
    \draw (\from,1) -- (\to,2);
  }
  \draw[gray] (0.5,0.5) rectangle (\to+0.5,2.5);
\end{tikzpicture}

\begin{tikzpicture}
  \foreach \from [count=\to] in {1,3,2} {
    \draw (\from,1) -- (\to,2);
  }
  \draw[gray] (0.5,0.5) rectangle (\to+0.5,2.5);
\end{tikzpicture}

% This one does not work:

\begin{tikzpicture}
  \foreach \list [count=\row] in {{2,3,1},{1,3,2}} {
    \foreach \from [count=\to] in \list {
      \draw (\from,\row) -- (\to,\row+1);
    }
  }
  \draw[gray] (0.5,0.5) rectangle (\to+0.5,\row+1.5);
\end{tikzpicture}

\end{document}

私が最終的に目指すものは次のとおりです。

望ましい結果

答え1

これは、TikZ マクロと組み合わせて LaTeX カウンターを使用します。すべてのカウンター操作はグローバルです。

\documentclass{article}
\usepackage{tikz}

\newcounter{to}
\newcounter{row}

\begin{document}


\begin{tikzpicture}
  \setcounter{to}{0}
  \foreach \from in {2,3,1} {
    \stepcounter{to}
    \draw (\from,1) -- ({\theto},2);
  }
  \draw[gray] (0.5,0.5) rectangle (\theto+0.5,2.5);
\end{tikzpicture}

\begin{tikzpicture}
  \setcounter{to}{0}
  \foreach \from in {1,3,2} {
    \stepcounter{to}
    \draw (\from,1) -- (\theto,2);
  }
  \draw[gray] (0.5,0.5) rectangle (\theto+0.5,2.5);
\end{tikzpicture}


\begin{tikzpicture}
  \setcounter{row}{0}
  \foreach \list in {{2,3,1},{1,3,2}} {
    \stepcounter{row}
    \setcounter{to}{0}
    \foreach \from in \list {
      \stepcounter{to}
      \draw (\from,\therow) -- (\theto,\therow+1);
    }
  }
  \draw[gray] (0.5,0.5) rectangle (\theto+0.5,\therow+1.5);
\end{tikzpicture}

\end{document}

デモ

答え2

このソリューションには、リストを複数回反復処理する必要があるという欠点がありますが、グローバル変数の設定を回避できます。

\documentclass{article}
\usepackage{tikz}
\begin{document}

\begin{tikzpicture}
  \foreach \list [count=\row] in {{2,3,1},{1,3,2}} {
    \foreach \from [count=\to] in \list {
      \draw (\from,\row) -- (\to,\row+1);
    }
  }
  \foreach \list [count=\count] in {{2,3,1},{1,3,2}} {
    \ifx \count \row
      \foreach \from [count=\to] in \list {
      }
      \draw[gray] (0.5,0.5) rectangle (\to+0.5,\row+1.5);
    \fi
  }
\end{tikzpicture}

\end{document}

最初のバージョンの問題は、\to使用しようとしたときにスコープ外だったことです。これは、スコープ内にあるときに使用します。

関連情報