又到了写论文的季节,对于代码狗来说,写一手好看的伪代码,对于让老师高看一眼,就有了重要的意义,下面就是一个讨论的链接
如何在word文档里面插入漂亮的伪代码?
里面说用Auraro好,但找了半天只有32位,安起来又复杂,恶心,就权当这项目死了
那怎么写好看的伪代码,答案当然是latex,下面就是我从这里找到的好东西,再加上overleaf

首先上overleaf,创建个项目,然后贴代码,伪代码就出来了
众所周知,latex恶心的在于其自由奔放的包,overleaf可以帮助我们省去这一糟心的过程
,至于用法,这里只用了一个latex包, a l g o r i t h m 2 e algorithm2e algorithm2e手册链接 and 备用链接
下面就是上图中,自己编写好可行的latex码

\def\SetClass{article}
\documentclass{\SetClass}
\usepackage[linesnumbered,lined,boxed,commentsnumbered,ruled,vlined]{algorithm2e}
\begin{document}
\IncMargin{1em}
\begin{algorithm}
\SetKwData{Left}{left}\SetKwData{This}{this}\SetKwData{Up}{up}
\SetKwFunction{Union}{Union}\SetKwFunction{FindCompress}{FindCompress}
\SetKwInOut{Input}{input}\SetKwInOut{Output}{output}
\Input{A bitmap $Im$ of size $w\times l$}
\Output{A partition of the bitmap}
\BlankLine
\emph{special treatment of the first line}\;
\For{$i\leftarrow 2$ \KwTo $l$}{
\emph{special treatment of the first element of line $i$}\;
\For{$j\leftarrow 2$ \KwTo $w$}{\label{forins}
\Left$\leftarrow$ \FindCompress{$Im[i,j-1]$}\;
\Up$\leftarrow$ \FindCompress{$Im[i-1,]$}\;
\This$\leftarrow$ \FindCompress{$Im[i,j]$}\;
\If(\tcp*[h]{O(\Left,\This)==1}){\Left compatible with \This}{\label{lt}
\lIf{\Left $<$ \This}{\Union{\Left,\This}}
\lElse{\Union{\This,\Left}}
}
\If(\tcp*[f]{O(\Up,\This)==1}){\Up compatible with \This}{\label{ut}
\lIf{\Up $<$ \This}{\Union{\Up,\This}}
\tcp{\This is put under \Up to keep tree as flat as possible}\label{cmt}
\lElse{\Union{\This,\Up}}\tcp*[h]{\This linked to \Up}\label{lelse}
}
}
\lForEach{element $e$ of the line $i$}{\FindCompress{p}}
}
\caption{disjoint decomposition}\label{algo_disjdecomp}
\end{algorithm}\DecMargin{1em}
\end{document}

简单说一些基础使用,SetKwData,就是定义变量,第一个大括号是定义标签,第二个大括号是定义实际显示的字符串

\SetKwData{Left}{left}
\SetKwData{This}{this}
\SetKwData{Up}{up}

在定义函数的时,第一个大括号也是定义标签,第二个大括号是实际显示的字符串

\SetKwFunction{Union}{Union}
\SetKwFunction{FindCompress}{FindCompress}

然后在右边截个图贴word里,妙了,真漂亮,不多说了,继续写论文了

2022.3.7 继续添加

上文中的latex只支持英文,但写论文时要的是中文,所以下面给出一个解决方案

很多文章里说用ctex或者CJK但用的时候都有问题,会让上面伪代码的格式变形

其实很简单,加上一个\usepackage{xeCJK},其他的都没加,用的时候直接写中文就好,不用加标签

\def\SetClass{article}
\documentclass{\SetClass}
\usepackage[linesnumbered,lined,boxed,commentsnumbered,ruled,vlined]{algorithm2e}
\usepackage{xeCJK}
\begin{document}
...
\SetKwFunction{Sort}{sort}\SetKwFunction{Array}{函数}
\SetKwFunction{Abs}{abs}
\SetKwInOut{Input}{输入}\SetKwInOut{Output}{output}
\Input{中文中文中文}
\Output{你好你好,我是输出}
...
\end{document}

简单demo截图,格式正常,中文显示正常

更多推荐

伪代码块编写(论文编写用)