TeX - LaTeX Asked on March 26, 2021
I have the following code:
documentclass{article}
usepackage{algorithm}
usepackage{algorithmic}
newcounter{ALC@tempcntr}% Temporary counter for storage
newcommand{LCOMMENT}[1]{%
setcounter{ALC@tempcntr}{arabic{ALC@rem}}% Store old counter
setcounter{ALC@rem}{1}% To avoid printing line number
item //#1 % Display comment + does not increment list item counter
setcounter{ALC@rem}{arabic{ALC@tempcntr}}% Restore old counter
}%
begin{document}
begin{algorithm}[!t]
caption{A sample algorithm.}
textbf{Input:} Some input.
textbf{Output:} Some output.
begin{algorithmic}[1]
LCOMMENT {1st Step:}
STATE Do something.
LCOMMENT {2nd Step:}
IF {$A geq B$}
STATE Do something.
LCOMMENT {3rd Step:}
ELSE
STATE Do something.
ENDIF
end{algorithmic}
end{algorithm}
end{document}
which produces the following algorithm. Note that I use a new command for comment (i.e. LCOMMENT) in order to have comments starting with // and, more importantly, to not use line numbering for comments.
However, in the above case, I would like the 3rd comment to have the same indentation as the next line in the algorithm (i.e. line 4) and not the same indentation as line 3. Is there a simple way to do this?
At each level beyond the first algorithmic
adds algorithmicindent
to the current indentation. One can access the level by looking at @listdepth
, so we need to add a negative space of @listdepth-1
times algorithmicindent
.
documentclass{article}
usepackage{algorithm}
usepackage{algorithmic}
newcounter{ALC@tempcntr}% Temporary counter for storage
newcommand{LCOMMENT}[1]{%
setcounter{ALC@tempcntr}{arabic{ALC@rem}}% Store old counter
setcounter{ALC@rem}{1}% To avoid printing line number
item removemargin // #1 % Display comment + does not increment list item counter
setcounter{ALC@rem}{arabic{ALC@tempcntr}}% Restore old counter
}
makeatletter
newcommand{removemargin}{hspace*{numexpr1-@listdepthrelaxalgorithmicindent}}
makeatother
begin{document}
begin{algorithm}[!t]
caption{A sample algorithm.}
textbf{Input:} Some input.
textbf{Output:} Some output.
begin{algorithmic}[1]
LCOMMENT {1st Step:}
STATE Do something.
LCOMMENT {2nd Step:}
IF {$A geq B$}
STATE Do something.
LCOMMENT {3rd Step:}
IF{x}STATE a LCOMMENT {what?}ELSE STATE b ENDIF % to show further indentation
ELSE
STATE Do something.
ENDIF
end{algorithmic}
end{algorithm}
end{document}
Correct answer by egreg on March 26, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP