我在创建数组(编程概念)的简单过程中错过了自己,并在数组下方画了一些线来指示某个范围。
我的实际状态如下
\documentclass[letterpaper,12pt]{article}
\usepackage{tikz}
\newcounter{nodeidx}
\setcounter{nodeidx}{1}
\usetikzlibrary{arrows.meta,
shapes.multipart}
\usetikzlibrary{arrows}
%++++++++++++++++++++++++++++++++++++++++
\usetikzlibrary{calc}
\newcommand{\nodes}[1]{%
\foreach \num in {#1}{
\node[minimum size=6mm, draw, rectangle] (\arabic{nodeidx}) at (\arabic{nodeidx},0) {\num};
\stepcounter{nodeidx}
}
}
\newcommand{\brckt}[4]{% from, to, lvl, text
\draw (#1.south west) ++($(-.1, -.1) + (-.1*#3, 0)$) -- ++($(0,-.1) + (0,-#3*1.25em)$) -- node [below] {#4} ($(#2.south east) + (.1,-.1) + (.1*#3, 0) + (0,-.1) + (0,-#3*1.25em)$) -- ++($(0,#3*1.25em) + (0,.1)$);%
}
\begin{document}
\begin{center}
\begin{center}
\begin{tikzpicture}
\pgftransparencygroup
\nodes{2, 4, 3, 1, 6, 7, 8, 9, 1, 7}
\endpgftransparencygroup
\pgftransparencygroup
\brckt{1}{6}{0}{Query(0, 5)}
\endpgftransparencygroup
\pgftransparencygroup
\brckt{4}{10}{0}{Query(3, 9)}
\endpgftransparencygroup
\end{tikzpicture}
\end{center}
\end{center}
\end{document}
我想避免线条之间的重叠,就像这张图片中那样
答案1
解决方案和一些提示:
- 无需外部计数器,你可以
count
使用foreach
- 您对括号的命令有点不必要的复杂。这里有一点我自己的品味,但我想你会喜欢我的。
- 一个
\usetikzlibrary
就足够了,可以让一切保持紧凑和有序。 - 现在
level
是一个可选参数,因此如果不需要则无需提供它。
输出
代码
\documentclass[tikz, margin=10pt]{standalone}
\usetikzlibrary{
calc,
%arrows.meta,
%shapes.multipart,
%arrows
}
\newcommand{\nodes}[1]{%
\foreach \num [count=\n starting from 0] in {#1}{% no need for an external counter
\node[minimum size=6mm, draw, rectangle] (n\n) at (\n,0) {\num};
}
}
\newcommand{\brckt}[4][1]{% [ lvl ] { from, to, text }
\coordinate (left) at ($(n#2.south west)+(-2mm,-1mm)$);
\coordinate (right) at ($(n#3.south east)+(2mm,-1mm)$);
\draw (left) -- ($(left)+(0,-1mm*#1)$) --node[below,midway,font=\scriptsize] {#4} ($(right)+(0,-1mm*#1)$) -- (right);
}
\begin{document}
\begin{tikzpicture}
%\pgftransparencygroup
\nodes{2, 4, 3, 1, 6, 7, 8, 9, 1, 7}
%\endpgftransparencygroup
%\pgftransparencygroup
\brckt[2]{0}{5}{Query(0, 5)}
%\endpgftransparencygroup
%\pgftransparencygroup
\brckt{3}{9}{~~~~~~~Query(3, 9)}% used ~ to push the label
%\endpgftransparencygroup
\end{tikzpicture}
\end{document}
答案2
使用循环、库chains
和positioning
,并确定括号(\brckt
)的不同振幅:
\documentclass[letterpaper,12pt]{article}
\usepackage{tikz}
\usetikzlibrary{chains,
positioning}
\newcommand{\brckt}[4]{% from, to, lvl, text
\draw (#1.south west) -- ++(0,-#3) -| node[pos=0.25, below] {#4} (#2.south east); % <---
}
\begin{document}
\begin{center}
\begin{tikzpicture}[
node distance = 2mm,
start chain = going right,
N/.style = {draw, minimum size = 5mm, inner sep=0pt, outer sep=1mm,
below=2mm, on chain} % <---
]
\foreach \i [count=\j] in {2, 4, 3, 1, 6, 7, 8, 9, 1, 7} % <---
\node (n\j) [N] {\i};
\brckt{n1}{n6}{1mm}{Query(0, 5)} % <---
\brckt{n4}{n10}{2mm}{Query(3, 9)}% <---
\end{tikzpicture}
\end{center}
\end{document}