\chapter{Motif}

\begin{algorithm}
	\caption{Brute-force search of a motif in a sequence}
	\begin{algorithmic}[1]
		\Function{FindMotif}{S: Array(n), M: Array(m)} {
			\Returns{list of position}
			\State $pos \gets \{\}$
			\State $i \gets 0$
			\While {$i < n - m + 1$} {
				\State $j \gets 0$
				\While {$j < m$ and S[i+j] $ = $ M[j]} {
					\State $j++$
				}
				\EndWhile
				\If {$j = m$}
				\State $pos \gets pos \cup \{i\}$
				\EndIf
				\State $i++$
			}
			\EndWhile
			\State \Return $pos$
		}
		\EndFunction
	\end{algorithmic}
	\label{alg:naive-motif-matching}
\end{algorithm}

\begin{algorithm}
	\caption{Knuth-Morris-Pratt algorithm}
	\begin{algorithmic}[1]
		\Function{KMP\_Search}{S: Array(n), M: Array(m)}
		\Returns{Integer}
		\State $table \gets \Call{KMP\_Table}{M}$
		\State $c \gets 0$ \Comment{Count the number of matches}
		\State $i \gets 0$
		\State $j \gets 0$
		\While {$i < n$}
		\If{$S[i] = M[i]$}
		\State $i \gets i + 1$
		\State $j \gets j + 1$
		\EndIf
		\If {$j = m$}
		\State $c \gets c + 1$
		\State $j \gets table[j-1]$
		\ElsIf {$j < n$ and $M[j] \neq S[i]$}
		\If {$j \neq 0$}
		\State $j \gets table[j-1]$
		\Else
		\State $i \gets i + 1$
		\EndIf
		\EndIf`
		\EndWhile
		\State \Return $c$
		\EndFunction

		\Function{KMP\_Table}{M: Array(m)}
		\State \textbf{Returns} Array(m)
		\State $previous \gets 0$
		\State $table \gets $ array of zeros of size m
		\For {$i = 0$; $i < m$; $i++$}
		\If {$M[i] = M[previous]$}
		\State $previous \gets previous + 1$
		\State $table[i] \gets previous$
		\State $i \gets i + 1$
		\Else
		\If {$previous = 0$}
		\State $previous \gets table[previous - 1]$
		\Else
		\State $table[i] \gets 0$
		\State $i \gets 1$
		\EndIf
		\EndIf
		\EndFor
		\EndFunction
	\end{algorithmic}
\end{algorithm}
