利用Overleaf使用Latex插入算法伪代码

目录


一个简单的例子:

我们使用的是Overleaf, 在线LaTeX编辑器进行编写,在项目的菜单中选择XeLaTeX编译器。

样式一(algorithm2e算法):

\def\SetClass{article}
\documentclass{\SetClass}
\usepackage[top=2cm, bottom=2cm, left=2.5cm, right=2.5cm]{geometry} %定义页边距
\usepackage[linesnumbered,ruled]{algorithm2e}
% \documentclass[1000pt]{article}
\usepackage{amsmath} %数学公式
\usepackage[UTF8]{ctex} %输出中文
\renewcommand{\thealgocf}{2} %这里用来定义算法1,算法2等

\begin{document}
\IncMargin{1em} % 页边距
\begin{algorithm}
    \SetAlgoLined %显示end
    \caption{Mobility Tree Construction}
    \SetKwInOut{Input}{Input}
    \SetKwInOut{Output}{Output}
    % 设置输入
    \Input{}
    % $$括起来表示这是一个数学表达式,会使用英文斜体表示. \\表示换行
    $X = n \times gene$, expression matrix for $n$ sample with $g$ genes \\
    % _表示下缀
    $X_i$ = expression matrix of sample \\
    % \delta是latex输入希腊字母δ的方式
    $\delta$: probability \\
    $f_{mlp}$: the model \\
    % 定义函数内容
    \SetKwFunction{MyFuns} {MyFuns}
    \SetKwProg{Fn}{Function}{:}{}
    \Fn{\MyFuns{$X$, $X_i$, $X_{func}$, $\delta$}} {
        setVariables($X$, $Score$) \\
        % 添加注释
        \tcp{\emph{This is an annotation}}\label{cmt} \\
        Train a network, $f_{\theta,0}$, using the samples from $D_L$  \\
        % for循环
        \For{$i$ in $1 : MaxIterations$}{
        Pseudo-label $D_U$ using $f_{\theta, i-1}$ \\
        $D_{selected} \leftarrow $ Select pseudo-labels using UPS \\
        $\tilde{D} \leftarrow D_L \bigcup D_{selected}$ \\
        Initiallize new network $f_{\theta, i}$ \\
        Train $f_{\theta, i}$ using the samples from $\tilde{D}$. \\
        $f_{\theta} \leftarrow f_{\theta, i}$ \\
        }
        \KwRet $f_{\theta}$
    }
\end{algorithm}
\DecMargin{1em} % 页边距
\end{document}

样例二(algorithm2e算法):

\def\SetClass{article}
\documentclass{\SetClass}
\usepackage[top=2cm, bottom=2cm, left=2.5cm, right=2.5cm]{geometry} %定义页边距
\usepackage[linesnumbered,ruled]{algorithm2e}
% \documentclass[1000pt]{article}
\usepackage{amsmath} %数学公式
\usepackage[UTF8]{ctex} %输出中文
\renewcommand{\thealgocf}{2} %这里用来定义算法1,算法2等

\begin{document}
\begin{algorithm}[H]
    \SetAlgoLined %显示end
	\caption{algorithm caption}%算法名字
	\KwIn{input parameters A, B, C}%输入参数
	\KwOut{output result}%输出
	some description\; %\;用于换行
	\For{condition}{
		only if\;
		\If{condition}{
			1\;
		}
	}
	\While{not at end of this document}{
		if and else\;
		\eIf{condition}{
			1\;
		}{
			2\;
		}
	}
	\ForEach{condition}{
		\If{condition}{
			1\;
		}
	}
	return 
\end{algorithm}
\end{document}

 样式三(algorithm算法):

%在菜单中,编译器选择XeLaTex
\documentclass[11pt]{ctexart}
\usepackage[top=2cm, bottom=2cm, left=2.5cm, right=2.5cm]{geometry} %定义页边距
\usepackage{algorithm}
\usepackage{algorithmicx}
\usepackage{algpseudocode}
\usepackage{amsmath} %数学公式
\usepackage[UTF8]{ctex} %输出中文
\floatname{algorithm}{Algorithm} %算法
\renewcommand{\algorithmicrequire}{\textbf{Input:}} %输入
\renewcommand{\algorithmicensure}{\textbf{Output:}} %输出
 
\begin{document}
\renewcommand{\thealgorithm}{2} %这里用来定义算法1,算法2等
    \begin{algorithm}
        \caption{K-Means聚类盲均衡算法} %标题
        \begin{algorithmic}[1] %每行显示行号,1表示每1行进行显示
            \Require 输入样本集$D$ = \{$x_1,x_2,...,x_N$\},分簇数$K=2$,最大迭代次数为$M$,从分簇样本中随机选取两点\{$u_1$,$u_2$\}作为初始质心
            \Ensure 样本分簇质心\{$C_1$,$C_2$\}
            \For{$m = 1 \to M$} //$m$表示迭代次数
                \State $C_1 \Leftarrow \emptyset, C_2 \Leftarrow \emptyset$ //初始化各簇
                \For{$i = 1,2,...,N$}     //$i$表示样本集编号
                    \State $d_{i1} \Leftarrow {\Vert x_i-u_1 \Vert}^2$, $d_{i2} \Leftarrow {\Vert x_i-u_2 \Vert}^2$ //计算$x_i$到两质心的欧式距离
                    \If {$d_{i1} \leq d_{i2}$}
                    \State $C_1 \Leftarrow C_1 \cup \{x_i\}$ //将$x_i$划分到相应的簇
                    \Else
                    \State $C_2 \Leftarrow C_2 \cup \{x_i\}$ %有时候需要用\来转译
                \EndIf
                \EndFor
                \State $\tilde{u_1} \Leftarrow \frac{1}{\vert C_1 \vert}\sum_{x \in C_1} x$, $\tilde{u_2} \Leftarrow \frac{1}{\vert C_2 \vert}\sum_{x \in C_2} x$ //重新计算各簇质心
                \If {$(\tilde{u_1} == u_1)\ and\ (\tilde{u_2} == u_2$} //各簇质心未改变,跳出循环
                    \State \textbf{break} from line 3 %\textbf为加粗
                    \Else
                    \State $u_1 \Leftarrow \tilde{u_1}, u_2 \Leftarrow \tilde{u_2}$ //更新各簇质心
                \EndIf
            \EndFor
            \State \Return $C_1, C_2$ //输出结果
        \end{algorithmic}
    \end{algorithm}
\end{document}

 样式四(algorithm算法):

%在菜单中,编译器选择XeLaTex
\documentclass[11pt]{ctexart}
\usepackage[top=2cm, bottom=2cm, left=2.5cm, right=2.5cm]{geometry} %定义页边距
\usepackage{algorithm}
\usepackage{algorithmicx}
\usepackage{algpseudocode}
\usepackage{amsmath} %数学公式
\usepackage[UTF8]{ctex} %输出中文
\floatname{algorithm}{Algorithm} %算法
\renewcommand{\algorithmicrequire}{\textbf{Input:}} %输入
\renewcommand{\algorithmicensure}{\textbf{Output:}} %输出
 
\begin{document}
\renewcommand{\thealgorithm}{2} %这里用来定义算法1,算法2等
    \begin{algorithm}
        \caption{K-Means聚类盲均衡算法} %标题
        \begin{algorithmic}[1] %每行显示行号,1表示每1行进行显示
            \Require 输入样本集$D$ = \{$x_1,x_2,...,x_N$\},分簇数$K=2$,最大迭代次数为$M$,从分簇样本中随机选取两点\{$u_1$,$u_2$\}作为初始质心
            \Ensure 样本分簇质心\{$C_1$,$C_2$\}
            \For{$m = 1 \to M$} //$m$表示迭代次数
                \State $C_1 \Leftarrow \emptyset, C_2 \Leftarrow \emptyset$ //初始化各簇
                \For{$i = 1,2,...,N$}     //$i$表示样本集编号
                    \State $d_{i1} \Leftarrow {\Vert x_i-u_1 \Vert}^2$, $d_{i2} \Leftarrow {\Vert x_i-u_2 \Vert}^2$ //计算$x_i$到两质心的欧式距离
                    \If {$d_{i1} \leq d_{i2}$}
                    \State $C_1 \Leftarrow C_1 \cup \{x_i\}$ //将$x_i$划分到相应的簇
                    \Else
                    \State $C_2 \Leftarrow C_2 \cup \{x_i\}$ %有时候需要用\来转译
                \EndIf
                \EndFor
                \State $\tilde{u_1} \Leftarrow \frac{1}{\vert C_1 \vert}\sum_{x \in C_1} x$, $\tilde{u_2} \Leftarrow \frac{1}{\vert C_2 \vert}\sum_{x \in C_2} x$ //重新计算各簇质心
                \If {$(\tilde{u_1} == u_1)\ and\ (\tilde{u_2} == u_2$} //各簇质心未改变,跳出循环
                    \State \textbf{break} from line 3 %\textbf为加粗
                    \Else
                    \State $u_1 \Leftarrow \tilde{u_1}, u_2 \Leftarrow \tilde{u_2}$ //更新各簇质心
                \EndIf
            \EndFor
            \State \Return $C_1, C_2$ //输出结果
            
            \State
            \Function{ConstructTree}{$traj, nary$}
            \State Initialize an empty tree $MT$ with no nodes and edges
            \State Initialize an empty dictionary variable $map$
            \State $len\gets$ The length of $traj$
            \State Initialize the dictionary variable $flags$ of length $len$
            \State \Call{AddChild}{$MT, traj, len-1, map, flags$}
            \State \Return{$MT$}
        \EndFunction
        \end{algorithmic}
    \end{algorithm}
\end{document}

下面详细讲解algorithm2e算法的使用

1、宏包参数的使用

这句代码表示引用宏包algorithm2e

\usepackage[linesnumbered,ruled,vlined]{algorithm2e}

下面是它的一些常用参数介绍

参数

作用

linesnumbered

显示行号

ruled

标题显示在上方,不加就默认显示在下方

vlined

代码段中用线连接

boxed

将算法插入在一个盒子里

基本语法

代码

作用

\;

行末添加行号并自动换行

\caption{ 算法名称}

插入算法名称

\KwData输入信息}

显示“Data:输入信息”

\KwIn{ 输入信息}

显示“Input:输入信息”

\KwOut{ 输出信息}

显示“Output:输出信息”

\KwResult{ 输入信息}

显示“Result:输出信息”

\For{ 条件}{ 循环语句}

For循环

\If{ 条件}{ 肯定语句}

If条件判断

\eIf{ 条件}{ 肯定语句}{ 否定语句}

If-else判断语句

\While{ 条件}{ 肯定语句}

While循环

\ForEach{ 条件}{ 执行语句}

ForEach遍历

\tcc{ 注释}

显示“\* 注释 *\

\tcp{ 注释}

显示“\\注释”

\SetAlgoLined

显示“每个结尾的end

\LinesNumbered

显示行号

2、修改Algorithm为中文

使用以下语句可将默认的“Algorithm”修改为中文“算法”

\renewcommand{\algorithmcfname}{算法}

3、修改Input、Output为中文

\SetKwInOut{KwIn}{输入}
\SetKwInOut{KwOut}{输出}

4、自定义算法编号

\renewcommand{\thealgocf}{3-1}

5、添加算法目录

\renewcommand{\listalgorithmcfname}{算\ 法\ 目\ 录}
% 生成算法目录命令
\listofalgorithms

总代码

\documentclass{ctexart}
\usepackage[ruled,vlined]{algorithm2e}

\begin{document}

\renewcommand{\listalgorithmcfname}{算\ 法\ 目\ 录}
% 生成算法目录命令
\listofalgorithms

\renewcommand{\algorithmcfname}{算法}
\SetKwInOut{KwIn}{输入}
\SetKwInOut{KwOut}{输出}

\begin{algorithm}
    \renewcommand{\thealgocf}{3-1}
    \SetAlgoLined %显示end
	\caption{algorithm caption}%算法名字
	\KwIn{input parameters A, B, C}%输入参数
	\KwOut{output result}%输出
	some description\; %\;用于换行
	\For{condition}{
		only if\;
		\If{condition}{
			1\;
		}
	}
	return 
\end{algorithm}
\begin{algorithm}
    \renewcommand{\thealgocf}{3-2}
    \SetAlgoLined %显示end
	\caption{algorithm caption}%算法名字
	\KwIn{input parameters A, B, C}%输入参数
	\KwOut{output result}%输出
	some description\; %\;用于换行
	\For{condition}{
		only if\;
		\If{condition}{
			1\;
		}
	}
	return 
\end{algorithm}
\end{document}

附录

均为基于 algorithm2e的。

1、“\\”和“\;”区别

\\换行后没有分号,而\;有。

2、返回

三种返回方式

\SetKwProg{Fn}{Function}{:}{end}
\Fn{FMain asda}{
  \KwRet $f_{\theta}$\;
  \Return{$f_{\theta}$}\;
  \textbf{return}{ $f_{\theta}$}\;
}

 3、定义函数Function

\SetKwProg{Fn}{Function}{:}{end}
\Fn{FMain asda}{
    这里是一个函数定义\\
}

4、添加斜体文本

\textit{AddChild(MT, traj, len-1, map, flags)}\;

5、附案例

\def\SetClass{article}
\documentclass{\SetClass}
\usepackage[top=2cm, bottom=2cm, left=2.5cm, right=2.5cm]{geometry} %定义页边距
\usepackage[linesnumbered,ruled]{algorithm2e}
% \documentclass[1000pt]{article}
\usepackage{amsmath} %数学公式
\usepackage[UTF8]{ctex} %输出中文
\renewcommand{\thealgocf}{2} %这里用来定义算法1,算法2等
 
\begin{document}
\begin{algorithm}[H]
    \SetAlgoLined %显示end
    \caption{Mobility Tree Construction}
    \label{alg:1}
    \KwIn{One of the user's trajectory $traj$; The number of branches in the tree $nary$;}
    \KwOut{The Mobility Tree $MT$ corresponding to the input trajectory}
    \SetKwProg{Fn}{Function}{:}{end}
    \Fn{AddChild(MT, traj, idx, map, flags)}{
        $node\gets traj_{idx}$\;
        $map_{idx}\gets$ The number of nodes in $MT$\;
        Add $node$ to $MT$\;
        \If{$idx > 0$ and $flag_{idx} != 0$}{
            $flag_{idx}\gets 0$\;
            $i\gets nary$\;
            \While{$i > 0$}{
                $child\gets$ \textit{AddChild(MT, traj, idx-i, map, flags)}\;
                $edge\gets$ $child$ to $node$  // $src \rightarrow dst$\;
                Add $edge$ to $MT$\;
            }
        }
        \Return{$node$}
    }

    \Fn{ConstructTree(traj, nary)}{
        Initialize an empty tree $MT$ with no nodes and edges\;
        Initialize an empty dictionary variable $map$\;
        $len\gets$ The length of $traj$\;
        Initialize the dictionary variable $flags$ of length $len$\;
        \textit{AddChild(MT, traj, len-1, map, flags)}\;
        \Return{$MT$}
    }
\end{algorithm}
\end{document}

6、空格

一个斜杠\加空格即可。

\ 

7、更多

写LaTex数学公式大全:LaTeX-Math-Symbols.pdf (msu.edu)

利用Overleaf使用Latex插入算法伪代码

利用Overleaf使用Latex插入算法伪代码

利用Overleaf使用Latex插入算法伪代码

利用Overleaf使用Latex插入算法伪代码

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
扎眼的阳光的头像扎眼的阳光普通用户
上一篇 2023年12月20日
下一篇 2023年12月20日

相关推荐