2018 06 21
算法伪代码排版工具CTeX
多少次你看到别人的的伪代码排版如此完美而惊艳,心中不免好奇,怎么设计的?今天,和大家一起学习一款流行的排版利器:CTeX
1排版效果展示
下面演示的是动态规划求最大连乘数组算法的伪代码,关于这个题目的详细介绍可参考:详解连续子数组的最大累乘之动态规划解法
利用的排版工具为CTeX,排版语言也非常容易上手。
2 排版语法
这个排版格式使用的包algorithmicx模式(命令的首字母大写),里面用的较多的 \State 用来声明后面的语句,大家看一看,接下来就可以动手为自己的算法排版伪代码了。
下面列出常用的语句对:
\begin{document} \end{document}
\caption{算法的名称}
\Require 表示算法的输入
\Ensure 表示算法的输出
\If {$left < right$} 表示 if 语句的条件,用一对 $ 括起来
\State $vara \gets varb $ 表示将 varb 赋值给 vara
\State $var\_a$ 表示声明变量 var_a,必须要带一个\_转义下划线
\State <text>
\If{<condition>} <text> \EndIf
\If{<condition>} <text> \Else <text> \EndIf
\If{<condition>} <text> \ElsIf{<condition>} <text> \Else <text> \EndIf
\For{<condition>} <text> \EndFor
\ForAll{<condition>} <text> \EndFor
\While{<condition>} <text> \EndWhile
\Repeat <text> \Until{<condition>}
\Loop <text> \EndLoop
\Function{<name>}{<params>} <body> \EndFunction
\State \Return <text>
\Comment{<text>}
如果调用 algorithmic 包要求命令所有字符都要大写
\STATE <text>
\IF{<condition>} \STATE{<text>} \ENDIF
\FOR{<condition>} \STATE{<text>} \ENDFOR
\FOR{<condition> \TO <condition> } \STATE{<text>} \ENDFOR
\FORALL{<condition>} \STATE{<text>} \ENDFOR
\WHILE{<condition>} \STATE{<text>} \ENDWHILE
\REPEAT \STATE{<text>} \UNTIL{<condition>}
\LOOP \STATE{<text>} \ENDLOOP
\REQUIRE <text>
\ENSURE <text>
\RETURN <text>
\PRINT <text>
\COMMENT{<text>}
\AND, \OR, \XOR, \NOT, \TO, \TRUE, \FALSE
3 排版代码
1\documentclass[11pt]{ctexart}
2\usepackage[top=2cm, bottom=2cm, left=2cm, right=2cm]{geometry}
3\usepackage{algorithm}
4\usepackage{algorithmicx}
5\usepackage{algpseudocode}
6\usepackage{amsmath}
7
8\floatname{algorithm}{算法}
9\renewcommand{\algorithmicrequire}{\textbf{输入:}}
10\renewcommand{\algorithmicensure}{\textbf{输出:}}
11
12\begin{document}
13 \begin{algorithm}
14 \caption{用动态规划求最大连乘数组}
15 \begin{algorithmic}[1] %每行显示行号
16 \Require $nums$ list
17 \Ensure 最大值
18 \Function {maxProduct}{$nums$}
19 \State $min\_prod \gets nums[0]$
20 \State $max\_prod \gets nums[0]$
21 \State $ret \gets nums[0]$
22 \State $n \gets len(nums)-1$
23 \For{$i=1$ to $n$}
24 \State $it \gets nums[i]$
25 \If {$it < 0$}
26 \State $min\_prod,max\_prod \gets$ \Call{swap}{$min\_prod, max\_prod$}
27 \EndIf
28 \State $max\_prod \gets max(it, it * max\_prod)$
29 \State $min\_prod \gets min(it, it * min\_prod)$
30 \State $ret \gets max(max\_prod, ret)$
31 \EndFor
32 \State \Return{$ret$}
33 \EndFunction
34 \State
35 \Function{swap}{$a,b$}
36 \State $tmp \gets a$
37 \State $a \gets b$
38 \State $b\gets tmp$
39 \State \Return{$a,b$}
40 \EndFunction
41 \end{algorithmic}
42 \end{algorithm}
43\end{document}
4 更多排版功能
CTeX还具备对公式的排版,文档的排版等强大的功能,更多详细的原理说明,可参考文章:https://www.cnblogs.com/jingwhale/p/4250296.html