ブルームフィルターを検索しているときにGitHubでこの単純なPHPクラスに出くわしました。これは「ブルームフィルター」という名前でしたが、どちらにしても「ハッシュテーブル」のようなものだと思います。理解するのは非常に簡単です。
単語のファイルを読み取り、単語ごとにハッシュ配列キーを作成します。次に、単語がハッシュ配列に存在するかどうかを確認できます。
実際の単語を配列のキーまたは値として保存し、その単語が配列に存在するかどうかを確認するのではなく、これを使用することの利点はありますか?理論的には、これはオーバーヘッドを追加して同じことを行うだけです。助けてください私は私が欠けているものを理解していますか?
<?php
class Dictionary {
private $words;
private $wordsHash;
public $hashLength;
public function __construct($filepath, $hashLength) {
$this->words = file($filepath);
$this->hashLength = $hashLength;
foreach($this->words as $word){
$this->wordsHash[$this->createHash($word)] = true;
}
echo 'words: ' . count($this->words) . ' hashes: ' . count($this->wordsHash) . "\n";
}
public function createHash($str){
$hash = substr(md5(trim($str)), 0, $this->hashLength);
return $hash;
}
public function checkDictionary($str){
$hash = $this->createHash(trim($str));
if(array_key_exists ($hash , $this->wordsHash)){
return true;
}
return false;
}
}
?>
dictionary.txtファイルには10,000語が含まれていますが、デモ用にいくつか表示します
der
die
und
in
den
von
zu
das
mit
sich
des
auf
für
ist
使用例:
<?php
$dictionary = new Dictionary('dictionary.txt', 30);
if($dictionary->checkDictionary('den')){
echo 'The Word den Exist in the Hash Table';
}else{
echo 'The Word den DOES NOT Exist in the Hash Table';
}
?>