sequence-algorithms/content/chapters/part1/1.tex

78 lines
1.7 KiB
TeX
Raw Normal View History

2024-03-05 12:35:55 +01:00
\chapter{Motif}
\begin{algorithm}
\caption{Brute-force search of a motif in a sequence}
\begin{algorithmic}[1]
2024-03-12 13:15:22 +01:00
\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$
}
2024-03-05 12:35:55 +01:00
\EndFunction
\end{algorithmic}
2024-03-12 13:15:22 +01:00
\label{alg:naive-motif-matching}
2024-03-05 12:35:55 +01:00
\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
2024-03-05 12:35:55 +01:00
\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
2024-03-05 12:35:55 +01:00
\EndFor
\EndFunction
\end{algorithmic}
\end{algorithm}