dcat52
dcat52

Reputation: 149

Generating random points then connecting points less than certain distance away

I currently have the code below which produces the later output. I would like to generate the 10 points randomly as I already am. But instead of having blue dashed lines connecting to the the location (0,0), I want them to connect to the other dots if the distance is less than 4cm away.

I attempted things such as storing the data into arrays but updating and accessing the values was not working. I attempted nested for loops but handling the seed became difficult. What is a good way to do this?

\documentclass{standalone}

\usepackage{tikz}

\begin{document}
\begin{tikzpicture}

\draw[step=0.5cm,color=gray] (-2.5,-2.5) grid (2.5,2.5);

  
\pgfmathsetseed{2}
\foreach \x in {1,...,10}
{
  \pgfmathrandominteger{\a}{-240}{240}
  \pgfmathrandominteger{\b}{-240}{240}
  \fill [color=red,anchor=center](\a*0.01,\b*0.01) circle (0.1);
  
  % CHANGE HERE
  \draw [color=blue,densely dotted] (\a*0.01,\b*0.01) -- (0.0,0.0);
};

\end{tikzpicture}
\end{document}

10x10 grid with randomly placed filled dots and dashed lines connecting to 0,0

Upvotes: 2

Views: 877

Answers (1)

dcat52
dcat52

Reputation: 149

I seemed to have figured out a solution (not ideal but works for this case).

The key was to use the \pgfmathparse for performing the if statement to get a 0 or 1 to use in \ifnum.

\documentclass{standalone}

\usepackage{tikz}
\usetikzlibrary{math}

\begin{document}
\begin{tikzpicture}

\draw[step=0.5cm,color=gray] (-2.5,-2.5) grid (2.5,2.5);

\pgfmathsetseed{2}
\foreach \x in {1,...,10}
{
  \pgfmathrandominteger{\a}{-240}{240}
  \pgfmathrandominteger{\b}{-240}{240}
  \fill [color=red,anchor=center](\a*0.01,\b*0.01) circle (0.1);

  \pgfmathsetseed{2}
  \foreach \y in {0,...,\x}
  {
    \pgfmathrandominteger{\c}{-240}{240}
    \pgfmathrandominteger{\d}{-240}{240}
    \tikzmath{\i=(\a*0.01-\c*0.01)^2;}
    \tikzmath{\j=(\b*0.01-\d*0.01)^2;}
    \tikzmath{\k=\i+\j;}
    \pgfmathparse{\k < 4.0 ? 1 : 0}
    \ifnum\pgfmathresult=1
      \draw [color=blue,densely dotted] (\a*0.01,\b*0.01) -- (\c*0.01,\d*0.01);
    \fi
  };
};

\end{tikzpicture}
\end{document}

enter image description here

Upvotes: 2

Related Questions