LaTeX Algorithm相关写法

1. 前言

创作开始时间:2022年9月28日23:33:52

如题,对LaTeX写伪代码作一些探索。

2. 正文

2.1. 导言区

\usepackage{algorithm}
\usepackage{algorithmicx}
\usepackage{algpseudocode}
\usepackage{setspace}

\errorcontextlines\maxdimen

\makeatletter
\newcommand*{\algrule}[1][\algorithmicindent]{\makebox[#1][l]{\hspace*{.5em}\thealgruleextra\vrule height \thealgruleheight depth \thealgruledepth}}%
\newcommand*{\thealgruleextra}{}
\newcommand*{\thealgruleheight}{.75\baselineskip}
\newcommand*{\thealgruledepth}{.25\baselineskip}

\newcount\ALG@printindent@tempcnta
\def\ALG@printindent{%
	\ifnum \theALG@nested>0% is there anything to print
	\ifx\ALG@text\ALG@x@notext% is this an end group without any text?
	% do nothing
	\else
	\unskip
	\addvspace{-1pt}% FUDGE to make the rules line up
	% draw a rule for each indent level
	\ALG@printindent@tempcnta=1
	\loop
	\algrule[\csname ALG@ind@\the\ALG@printindent@tempcnta\endcsname]%
	\advance \ALG@printindent@tempcnta 1
	\ifnum \ALG@printindent@tempcnta<\numexpr\theALG@nested+1\relax% can't do <=, so add one to RHS and use < instead
	\repeat
	\fi
	\fi
}%
\usepackage{etoolbox}
%\AtBeginEnvironment{algorithmic}{\footnotesize}
\patchcmd{\ALG@doentity}{\noindent\hskip\ALG@tlm}{\ALG@printindent}{}{\errmessage{failed to patch}}
\makeatother

\newbox\statebox
\newcommand{\myState}[1]{%
	\setbox\statebox=\vbox{#1}%
	\edef\thealgruleheight{\dimexpr \the\ht\statebox+1pt\relax}%
	\edef\thealgruledepth{\dimexpr \the\dp\statebox+1pt\relax}%
	\ifdim\thealgruleheight<.75\baselineskip
	\def\thealgruleheight{\dimexpr .75\baselineskip+1pt\relax}%
	\fi
	\ifdim\thealgruledepth<.25\baselineskip
	\def\thealgruledepth{\dimexpr .25\baselineskip+1pt\relax}%
	\fi
	\State #1%
	\def\thealgruleheight{\dimexpr .75\baselineskip+1pt\relax}%
	\def\thealgruledepth{\dimexpr .25\baselineskip+1pt\relax}%
}

2.2. 将长算法分割

直接在分割点粘贴如下代码即可:

\algstore{bkbreak}
\end{algorithmic}
\end{algorithm}


\begin{algorithm}
\begin{algorithmic}[1]
\algrestore{bkbreak}

2.3. 调整算法文本字体大小

在导言区加入:

\usepackage{etoolbox}
\AtBeginEnvironment{algorithmic}{\footnotesize}

参考:

  • Smaller font size of the algorithm description? https://tex.stackexchange.com/questions/12110/smaller-font-size-of-the-algorithm-description

2.4. 调整算法行距

参考这个即可

  • Reduce vertical spacing in the algorithm environment https://tex.stackexchange.com/questions/16059/reduce-vertical-spacing-in-the-algorithm-environment

3. 小结

以上。
创作结束时间:2022年9月28日23:37:33

猜你喜欢

转载自blog.csdn.net/weixin_39278265/article/details/127099037