LoginSignup
5
5

TeXの擬似コードでネスト(入れ子)を見やすく表現

Last updated at Posted at 2018-02-15

はじめに

TeXにて論文執筆中、擬似コードを記述する場面があった。
パッケージは、algorithmic.styを使用。
その際、if文をネストする必要があったのだが、

%パッケージインポート
\usepackage{algpseudocode,algorithm}

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

\If{}
\If{} 〜〜 \EndIf
\EndIf

\end{algorithmic}
\end{algorithm}

と記述すると、

スクリーンショット 2018-02-15 10.53.45.png

のように表示され、見づらくなってしまう。

しかし、

\algnewcommand{\IIf}[1]{\State\algorithmicif\ #1\ \algorithmicthen} \algnewcommand{\EndIIf}{\unskip\ \algorithmicend\ \algorithmicif}
を擬似コード前で記述し、ワンラインでif文を表現したい部分にて、

\IIf{〜} 〜〜 \EndIIf

と記述することで表現できる。

改善後

%パッケージインポート
\usepackage{algpseudocode,algorithm}

%ワンライナーで表現するため
\algnewcommand{\IIf}[1]{\State\algorithmicif\ #1\ \algorithmicthen}
\algnewcommand{\EndIIf}{\unskip\ \algorithmicend\ \algorithmicif}

\begin{algorithm}
\begin{algorithmic}[1]
\caption{擬似コード}
\If{$x = 1$}
\IIf{$y = 1$}  yを出力 \EndIIf
\EndIf

\end{algorithmic}
\end{algorithm}
スクリーンショット 2018-02-15 11.00.52.png

また、end ifを除くことも可能である。
その際は、\EndIIfを除くだけで良い。

スクリーンショット 2018-02-15 11.04.48.png

これでネストの表現が見やすくなった。

参考

Algorithmic: Put If and EndIf into same line @StackExchange

5
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5