I have been trying to generate the Hilbert curve in tikz: https://www.kerrymitchellart.com/tutorials/hilbert/hilbert-tutorial.html.
This is my attempt so far (vary the integer macro \i from 1 onward).
I do not know how to rotate them properly from iteration 3 onward, and I don't know how to connect them from iteration 3 onward.
Not very applicable, but related: TikZ: Hilbert curves
Maybe someone can understand this: https://www.compuphase.com/hilbert.htm
\documentclass[
tikz
,border = 1cm
]{standalone}
\begin{document}
\begin{tikzpicture}
\draw[help lines] (-1,-1) grid (1,1);
\pgfmathsetmacro{\i}{4}
\pgfmathsetmacro{\step}{ifthenelse(\i==1,\i-1,1)*(1/2)^(\i-1)}
\foreach \x[parse = true] in {1,...,2^(\i-1)} {
\pgfmathsetmacro{\xshift}{
ifthenelse(\i==1,0,-1)+
((\x-1)/2^(\i-2)+\step)
}
\foreach \y[parse = true] in {1,...,2^(\i-1)} {
\pgfmathsetmacro{\yshift}{
ifthenelse(\i==1,0,-1)+
((\y-1)/2^(\i-2)+\step)
}
\draw[
red
,xshift = \xshift cm
,yshift = \yshift cm
,rotate= {
ifthenelse(
\i>1
,ifthenelse(
mod(\y,2)!=0,2*\x+1,0
)*90
,0
)
}
]
({-(0.5)^(\i)},{-(0.5)^(\i)})
--
({-(0.5)^(\i)},{(0.5)^(\i)})
--
({(0.5)^(\i)},{(0.5)^(\i)})
--
({(0.5)^(\i)},{-(0.5)^(\i)})
;
\pgfmathparse{\i>1 && mod(\x,2)==1 && mod(\y,2)==1}
\ifnum\pgfmathresult=1
\draw[
red
,xshift = \xshift cm
,yshift = \yshift cm
,rotate= {
ifthenelse(
\i>1
,ifthenelse(
mod(\y,2)!=0,2*\x+1,0
)*90
,0
)
}
]
({-(0.5)^(\i)-\step},{-(0.5)^(\i)})
--
({-(0.5)^(\i)},{-(0.5)^(\i)})
;
\fi
\pgfmathparse{\i>1 && mod(\x,2)==0 && mod(\y,2)==1}
\ifnum\pgfmathresult=1
\draw[
red
,xshift = \xshift cm
,yshift = \yshift cm
,rotate= {
ifthenelse(
\i>1
,ifthenelse(
mod(\y,2)!=0,2*\x+1,0
)*90
,0
)
}
]
({(0.5)^(\i)},{-(0.5)^(\i)})
--
({(0.5)^(\i)+\step},{-(0.5)^(\i)})
;
\fi
\pgfmathparse{\i>1 && mod(\x,2)==0 && mod(\y,2)==0}
\ifnum\pgfmathresult=1
\draw[
red
,xshift = \xshift cm
,yshift = \yshift cm
,rotate= {
ifthenelse(
\i>1
,ifthenelse(
mod(\y,2)!=0,2*\x+1,0
)*90
,0
)
}
]
({-(0.5)^(\i)},{-(0.5)^(\i)})
--
({-(0.5)^(\i)-\step},{-(0.5)^(\i)})
;
\fi
}
}
\end{tikzpicture}
\end{document}