TransWikia.com

About algorithm package

TeX - LaTeX Asked by Joncarre on August 4, 2021

I’m making an algorithm figure using usepackage[ruled, lined, linesnumbered, commentsnumbered, longend]{algorithm2e} and usepackage{algpseudocode}.

documentclass{article}

usepackage[ruled, lined, linesnumbered, commentsnumbered, longend]{algorithm2e}
usepackage{xcolor}
usepackage{algpseudocode}

begin{document}
begin{algorithm}
    KwResult{Best solution found for distribution}
    Population  initialization

    For{population size}{
        execute phasesComment{Mutation and crossover}
        
        If{elitism}{ 
            $population[0] = fittest$ Comment{Next evolution}
         }
    }
    KwRet{$fittest$}
    caption{Genetic algorithm}label{alg:genetic}
end{algorithm}
end{document}

enter image description here

and I’d like to add two details:

  1. Add a Require tag. I tried to add it using Require but it doesn’t work. Do I need another package additionally? Something like:

enter image description here

  1. Change the style of the number lines, similar to these ones:

enter image description here

I appreciate any help/info. Thanks!

One Answer

Don't mix the use of algorithm packages like algorithm2e and algorithmicx (which provides algpseudocode). You should stick to one. In your case it seems like algorithm2e provides the functionality that you're interested in, so build on that.

The minimal example provides KwRequire and a new Comment, together with the appropriate line number formatting.

enter image description here

documentclass{article}

usepackage[ruled,lined,linesnumbered]{algorithm2e}
DontPrintSemicolon

% Set algorithm keyword formatting
newcommand{Var}{textup}
newcommand{Comment}{tcc*[r]}
SetKwComment{tcc}{$triangleright$~}{}
SetCommentSty{normalfont}
SetKwInput{KwRequire}{Require}
% Set algorithm line numbers
SetNlSty{}{}{:}

begin{document}

begin{algorithm}
  KwRequire{Some data input}
  KwResult{Best solution found for distribution}
  Population initialization;
  For{population size}{%
    execute phases Comment{Mutation and crossover}
    If{elitism}{%
      $Var{population[0]} = Var{fittest}$ Comment{Next evolution}
    }
  }
  KwRet{$Var{fittest}$}
  caption{Genetic algorithm}
end{algorithm}

end{document}

Correct answer by Werner on August 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP