I am trying to recursively draw Ck x Ck, where Ck is the k-th iteration of a Cantor set. I have a command which recursively calls itself four times. If I pass N
as parameter #6
, the output should be 4N
little squares. But it only works for N
= 1, 2. If I do anything higher, I only get 4 squares, spaced out in the four corners. They are the right size, but there aren't enough of them.
Apparently, the problem has something do with \pgfmathtruncatemacro\C{#6 - 1}
. As a test I inserted \draw (0,0) circle (#6);
right before this line, and then right after this line, and the output was NOT always the same. It seems that \pgfmathtruncatemacro\C{#6 - 1}
somehow changes the value of #6
(in the SAME level of recursion), but I don't see why.
\usepackage{tikz, pgf, ifthen}
\newcommand\cantorsquare[6]{ %x y x y coordinates, dissection coordinates, nesting
%the coordinates are listed in the same order as coordinates for a rectangle
\ifthenelse{#6 = 0} %base case
{
\fill (#1, #2) rectangle (#3, #4);
}
{
{
%find the coordinates for the first smaller square
\pgfmathsetmacro\A{#1 + (1 - #5) * (#3 - #1) / 2}
\pgfmathsetmacro\B{#2 + (1 - #5) * (#4 - #2) / 2}
\pgfmathtruncatemacro\C{#6 - 1}
\cantorsquare{#1}{#2}{\A}{\B}{#5}{\C}
}
{
\pgfmathsetmacro\A{#1 + (1 - #5) * (#3 - #1) / 2}
\pgfmathsetmacro\B{#4 - (1 - #5) * (#4 - #2) / 2}
\pgfmathtruncatemacro\C{#6 - 1}
\cantorsquare{#1}{\B}{\A}{#4}{#5}{\C}
}
{
\pgfmathsetmacro\A{#3 - (1 - #5) * (#3 - #1) / 2}
\pgfmathsetmacro\B{#2 + (1 - #5) * (#4 - #2) / 2}
\pgfmathtruncatemacro\C{#6 - 1}
\cantorsquare{\A}{#2}{#3}{\B}{#5}{\C}
}
{
\pgfmathsetmacro\A{#3 - (1 - #5) * (#3 - #1) / 2}
\pgfmathsetmacro\B{#4 - (1 - #5) * (#4 - #2) / 2}
\pgfmathtruncatemacro\C{#6 - 1}
\cantorsquare{\A}{\B}{#3}{#4}{#5}{\C}
}
}
}
\begin{document}
\begin{tikzpicture} \cantorsquare{0}{0}{5}{5}{0.3}{3} \end{tikzpicture}
\end{document}
sa-tikz
package (where sa stands for switching architectures). Cantor Networks indeed are are just m parallel Benes Networks, andsa-tikz
exploits an embedded algorithm to deal with such recursion (more details in the appendix of the documentation). Indeed it's quite easy to draw the modules, but having automatically the interconnections it's a bit complicated and notice that the algorithm works for any dimension of the network.