
목록 목록이 있고 \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
사용하려고 할 때 범위를 벗어났다는 것입니다. 아직 범위 내에 있을 때 이를 사용합니다.