안녕하세요 저는 Rabin-Karp 알고리즘을 구현하기 위해 PHP 클래스를 작성하고 있습니다. 내가 해킹 부분에 문제가 있습니다. 이 코드는 문자의 일부와 일치하지 않습니다. 다시 해싱 문제로 인해 해시 코드와 일치하지 않으므로 그만 두어야했습니다. 누군가 나를 이해하도록 도와주세요.PHP를 사용한 Rabin-Karp 알고리즘 구현
<?php
class RabinKarp
{
/**
* @var String
*/
private $pattern ;
private $patternHash ;
private $text ;
private $previousHash ;
/**
* @var Integer
*/
private $radix ;
private $prime ;
private $position ;
/**
* Constructor
*
* @param String $pattern - The pattern
*
*/
public function __construct($pattern)
{
$this->pattern = $pattern;
$this->radix = 256;
$this->prime = 100007;
$this->previousHash = "";
$this->position = 0;
$this->patternHash = $this->generateHash($pattern);
}
private function generateHash($key)
{
$charArray = str_split($key);
$hash = 0;
foreach($charArray as $char)
{
$hash = ($this->radix * $hash + ord($char)) % $this->prime;
}
return $hash;
}
public function search($character)
{
$this->text .= $character;
if(strlen($this->text) < strlen($this->pattern))
{
return false;
}
else
{
$txtHash = 0;
echo $this->previousHash . "<br/>";
if(empty($this->previousHash))
{
$txtHash = $this->generateHash($this->text);
$this->previousHash = $txtHash;
$this->position = 0;
}
else
{
// The issue is here
$charArray = str_split($this->text);
$txtHash = (($txtHash + $this->prime) - $this->radix * strlen($this->pattern) * ord($charArray[$this->position]) % $this->prime) % $this->prime;
$txtHash = ($txtHash * $this->radix + ord($character)) % $this->prime;
$this->previousHash = $txtHash;
}
if($txtHash == $this->patternHash)
{
echo "Hash Match found";
}
}
}
}
$x = new RabinKarp("ABC");
$x->search("Z");
$x->search("A");
$x->search("B");
$x->search("C");
?>
감사합니다. 캐릭터가 처음 일치하는 창을 들어갈 때 ord(c)
에 기여하고, 해시 이후
이 알고리즘은 다중 바이트 문자열 값에서 작동합니까? 그렇다면 아마 길이를 계산할 때'mb_' 함수를 사용해야합니다. –
이 알고리즘은 직렬 전송으로 작동하도록 작성되었습니다. 한 번에 한 문자 씩 순차적으로 가져옵니다. 캐릭터를 받으면 검색을 시작합니다. 위의 코드는 나를 위해 잘 작동합니다. 다시 해싱 할 때만 문제가 발생합니다. 실제로 다시 해싱 값이 잘못되었습니다. –
@PrasadRajapaksha 안녕하세요 Mr. Prasad .. 고정 코드를 게시 해주세요. 내가 PHP와 여러 패턴에 대한 알고리즘을 rabin karp의 구현을 찾고 있어요. 제발 ... 사전에 감사합니다 – Ayuktia