[Tex/LaTex] Modular arithmetic on node names in TikZ


Say I have a bunch of nodes I've already created in TikZ—maybe v0, v1, …, vn-1. I'd like to connect certain of these nodes in a systematic way, by doing arithmetic on the indices, ideally mod n. For example, something like

\foreach \i \in {0,1,...,n-1}
{\draw[->] (v\i) -- (v\{i+2})}

But that doesn't work, and I can't seem to figure out the right syntax. And when I try to do complicated things with \pgfmathmod to do do the modular arithmetic on the node names, instead of the arrows connecting nicely between the nodes, I get the arrow connecting across the node to an inappropriate edge.

When I try something like
\foreach \i / \j in {0 / 2, ..., n-2 / n}{ (v\i) -- (v\j)} I get a strange error message "no node named v0" (or something like that).

Any suggestions? This seems like a rather obvious thing to want to be able to do.

Best Answer

The let command is useful here and allows for "inline computation":

  \foreach \i in {0,...,9} \draw (\i*36:2cm) node(\i){\i};
  \foreach \i in {0,...,9} \draw let \n1={int(mod(\i+2,10))} in (\i) -- (\n1);

the result