|||
想在latex中以这样的版式描述算法:
1 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx|
xxxxxxxxxxxxxxxxxxxxxxx/
2 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/
3 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/
4 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/
5 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx|
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx|
xxxxxxxxxxxxxxxxxx/
6 xxxxxxxxxxxxxxx/
7 xxxxxxxxxxxxx/
8 xxxxxxxxx/
说明:
1)“算法行”指带标号的行,“文本行”指行文产生的行,如上段算法描述中有8 个算法行,11 个文本行。
2)“|”表示右边界(自动换行),“/”表示硬回车(手动换行)。
(将上述算法版式复制到记事本中,可发现右边界实际上都是垂直对齐的。)
要求:
1)算法不浮动,能够跨页;
2)每个算法行的行号都在最左端,垂直对齐,连续编号;
3)每个算法行到达右边界(用“|”表示)后,自动换行;且该算法行的后续文本行均向右缩进若干(比如2个字符)距离,其版式类似于Word中的“悬挂缩进”;参见第1、第5 算法行;
4)每产生一次嵌套,嵌套的算法行除标号外,均整体向右缩进若干(比如4个字符)距离;参见第4、第5、第6 算法行。
说明:为什么没有使用algorithm2e和clrscode宏包。
1)algorithm2e产生的算法像图片和表格一样,是浮动的;
2)algorithm2e产生的算法不能跨页;
3)algorithm2e产生的算法,处理超长行时能自动换行,但不能实现悬挂缩进;
4)clrscode产生的算法风格很好很独特,但个人还是喜欢在for、while、if之后有end的算法书写方式;
5)clrscode产生的算法不能处理超长行;
6)clrscode产生的算法不能跨页。
在bbs.ctex.org上发帖询问,经过LeoLiu的帮助,终于实现所要求的算法版式。原帖见http://bbs.ctex.org/forum.php?mod=viewthread&tid=62650。下面贴出代码及排版效果图,与大家共享。
\documentclass{article}
% Thanks to LeoLiu at http://www.ctex.org.
\newcounter{algleo}
\newlength{\lefttab}
\newlength{\numberoffset}
\setlength{\numberoffset}{-1em}
\newenvironment{algleo}%
{\trivlist
\topsep=0pt\parsep=0pt\itemsep=0pt
\def\li{\item\refstepcounter{algleo}\makebox[0.8em][r]{\thealgleo\hspace{\numberoffset}}
\hangafter1\hangindent1.8em\noindent}%
\def\linonumber{\item\makebox[0.8em][r]{\hspace{\numberoffset}}
\hangafter1\hangindent1.8em\noindent}%
\def\linooffset{\item\hangafter1\hangindent1em\noindent}%
\addtolength{\lefttab}{1.25em}
\addtolength{\numberoffset}{1.25em}
\leftskip=\lefttab}%
{\endtrivlist}
\begin{document}
\section{The Algorithm}
\setcounter{algleo}{0}
\begin{algleo}
\linonumber Algorithm $\cal A$.
\li \label{step - alga init}This is a normal line.
\li This is a very long line. How to use \LaTeX~to deal with this line? This is a
very long line. How to use \LaTeX~to deal with this line?
\li {\bf while} I want to continue {\bf do}
\begin{algleo}
\li This is a nested normal line.
\li This is a very long line. How to use \LaTeX~to deal with this line?
This is a very long line. How to use \LaTeX~to deal with this line?
\li {\bf for} $i \leftarrow 1$ {\bf to} 100 {\bf do}
\begin{algleo}
\li This is a nested normal line.
\li This is a very long line. How to use \LaTeX~to deal with this line?
This is a very long line. How to use \LaTeX~to deal with this line?
\end{algleo}
\li {\bf end}
\end{algleo}
\li {\bf end}
\li {\bf return} nothing.
\end{algleo}
In step \ref{step - alga init}, the algorithm does some initializing work.
In step \ref{step - alga init}, the algorithm does some initializing work.
\end{document}
(请使用WORD的全角半角转换功能将上述代码转成半角。方法:WORD“开始”按钮栏中点击“大小写转换”,在下拉菜单中选择“全角”或“半角”。)
最后实现的排版效果如下所示:
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-11-23 18:09
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社