我希望轻松获得类似此图的东西,以便说明几种排序算法。
为了生成一行,我想使用以下类型的命令,其中值的数量不是预先固定的。
\list{\style1}{value1}{\style2}{value2}{\style3}{value3}
这里\style
可以定义背景和边框的颜色。
答案1
这是对 Peter Grill 的评论的评论/回答原始答案(+1)。
该\List
宏采用一个可选参数,即如果未指定则应该使用的样式(即…,<entry>,…
)。
我还擅自使用密钥来node distance
代替硬编码的(0.5*\i cm,0)
位置。
代码
\documentclass{article}
\usepackage{tikz}
\usepackage{xstring}
\tikzset{
raw sort entry/.style={rectangle, thick, draw, node distance=1.5em},
sort entry black/.style={raw sort entry, black, fill=white},
sort entry blackgray/.style={raw sort entry, black, fill=gray!25},
s1/.style={raw sort entry, red, fill=yellow!30},
s2/.style={raw sort entry, blue, fill=green!20},
s3/.style={raw sort entry, violet, fill=orange!25}
}
\newcommand*{\List}[2][sort entry black]{%
\par\noindent%
\edef\listtoprocess{#2}%
\def\ListToProcess{}%
\begin{tikzpicture}[inner sep=2pt, outer sep=0]
\foreach \content in \listtoprocess{
\IfSubStr{\content}{/}{% true
\xdef\ListToProcess{\ListToProcess,\content}
}{% false
\xdef\ListToProcess{\ListToProcess,#1/\content}
}
}
\StrGobbleLeft{\ListToProcess}{1}[\ListToProcess]% removes the first comma (\listToProcess is empty at the start)
\foreach [count=\i] \Style/\Value in \ListToProcess {
\ifnum\i=1\relax
\node [raw sort entry, \Style] (sortnode\i) {\Value};
\else
\node [raw sort entry, right of=sortnode\number\numexpr\i-1\relax, \Style] (sortnode\i) {\Value};
\fi
}
\end{tikzpicture}%
}
\begin{document}
\List{s1/1, 2, s3/3}
\List[sort entry blackgray]{s2/1, s1/2, s1/3, 1, s2/2, s3/3, s2/2, s2/3}
\List[s1]{1,2,/3,/2,3}% /3 and /2 falls back to no explicit \Style, so the resulting style is that from the \node [raw sort entry, …]
\end{document}
输出
答案2
为了允许任意数量的参数,我建议使用略有不同的语法,即以以下形式提供逗号分隔的列表:
<style>/<value>, <style>/<value>, <style>/<value>, ...
代码:
\documentclass{article}
\usepackage{tikz}
\tikzset{style1/.style={thick, draw=red,fill=yellow!30}}
\tikzset{style2/.style={thick, draw=blue,fill=green!20}}
\tikzset{style3/.style={thick, draw=violet,fill=orange!25}}
\newcommand*{\List}[1]{%
\par\noindent%
\begin{tikzpicture}[inner sep=2pt, outer sep=0]
\edef\ListToProcess{#1}% Allows for parapamater to be defined via a macro.
\foreach [count=\i] \Style/\Value in \ListToProcess {
\node [rectangle,\Style] at (0.5*\i cm,0) {\Value};
};
\end{tikzpicture}
}
\begin{document}
\List{style1/1, style2/2, style3/3}
\List{style2/1, style1/2, style1/3, style1/1, style2/2, style3/3, style2/2, style2/3}
\List{style3/1, style2/2, style2/3, style1/2, style1/3}
\end{document}