我可以生成随机点,但如何排除特定值或值范围?例如,排除 8 或排除 10-20。
\begin{pgfpicture}
\foreach \x in {1,...,1000}{
\pgfmathrandominteger{\a}{1}{100}
\pgfmathrandominteger{\b}{1}{100}
\pgfpathcircle{\pgfpoint{+\a pt}{+\b pt}}{+1pt}
\color{blue!40!white} \pgfsetstrokecolor{blue!80!black}
\pgfusepath{stroke, fill}
}
\end{pgfpicture}
答案1
可以使用命令排除 10 到 20 的范围\ifnum
:
\documentclass{article}
\usepackage{pgf}
\usepackage{pgffor}
\newif\ifok
\begin{document}
\begin{pgfpicture}
\pgfsetfillcolor{blue!40!white}
\pgfsetstrokecolor{blue!80!black}
\foreach \x in {1,...,1000}{
\oktrue
\pgfmathrandominteger{\a}{1}{100}
\ifnum\a>9 \ifnum\a<21 \okfalse \fi\fi
\ifok
\pgfmathrandominteger{\b}{1}{100}
\ifnum\b>9 \ifnum\b<21 \okfalse\fi\fi
\ifok
\pgfpathcircle{\pgfpoint{+\a pt}{+\b pt}}{+1pt}
\pgfusepath{stroke, fill}
\fi
\fi
}
\end{pgfpicture}
\end{document}
顺便说一句,颜色设置是恒定的,并且被移到循环之外。
以下变体保持样本数量不变,但仅为和生成 89 个不同的值,\a
并\b
调整随机处理器的输出,使 10 和 20 之间留出 11 个值的间隙:
\documentclass{article}
\usepackage{pgf}
\usepackage{pgffor}
\begin{document}
\begin{pgfpicture}
\pgfsetfillcolor{blue!40!white}
\pgfsetstrokecolor{blue!80!black}
\foreach \x in {1,...,1000}{
\pgfmathrandominteger{\a}{1}{89}
\pgfmathrandominteger{\b}{1}{89}
\ifnum\a>9
\pgfmathtruncatemacro\a{\a+11}
\fi
\ifnum\b>9
\pgfmathtruncatemacro\b{\b+11}
\fi
\pgfpathcircle{\pgfpoint{+\a pt}{+\b pt}}{+1pt}
\pgfusepath{stroke, fill}
}
\end{pgfpicture}
\end{document}
答案2
您可以使用强大的expl3
条件:
\documentclass{article}
\usepackage{pgf}
\usepackage{pgffor}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\exclude}{mm}
{
\tl_set:Nn \l_eightsaregreat_exclude_tl { \c_false_bool }
\clist_map_inline:nn { #1 }
{
\tl_put_right:Nn \l_eightsaregreat_exclude_tl
{
|| \int_compare_p:n { ##1 }
}
}
\bool_if:VF \l_eightsaregreat_exclude_tl { #2 }
}
\tl_new:N \l_eightsaregreat_exclude_tl
\cs_generate_variant:Nn \bool_if:nF { V }
\ExplSyntaxOff
\begin{document}
\begin{pgfpicture}
\pgfsetfillcolor{blue!40!white}
\pgfsetstrokecolor{blue!80!black}
\foreach \x in {1,...,1000}{
\pgfmathrandominteger{\a}{1}{100}
\pgfmathrandominteger{\b}{1}{100}
\exclude{\a=8, 10 <= \a <= 20,\b<5, 30 <= \b <= 50}
{
\pgfpathcircle{\pgfpoint{+\a pt}{+\b pt}}{+1pt}
\pgfusepath{stroke, fill}
}
}
\end{pgfpicture}
\end{document}
条件以“或”的形式连接起来,并以假条件来保持平衡,只有当条件为假时才会执行代码。