Created
October 22, 2025 07:18
-
-
Save saeedvir/e9f1d87ade2850396847bbfe046cccd4 to your computer and use it in GitHub Desktop.
php Bloom Filter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| class BloomFilter | |
| { | |
| protected int $size; | |
| protected int $hashCount; | |
| protected array $bitArray; | |
| public function __construct(int $size = 1000, int $hashCount = 3) | |
| { | |
| $this->size = $size; | |
| $this->hashCount = $hashCount; | |
| $this->bitArray = array_fill(0, $size, 0); | |
| } | |
| protected function getHashes(string $item): array | |
| { | |
| $hashes = []; | |
| for ($i = 0; $i < $this->hashCount; $i++) { | |
| $hash = crc32($item . $i); | |
| $index = $hash % $this->size; | |
| $hashes[] = $index; | |
| } | |
| return $hashes; | |
| } | |
| public function add(string $item): void | |
| { | |
| foreach ($this->getHashes($item) as $hash) { | |
| $this->bitArray[$hash] = 1; | |
| } | |
| } | |
| public function mightContain(string $item): bool | |
| { | |
| foreach ($this->getHashes($item) as $hash) { | |
| if ($this->bitArray[$hash] === 0) { | |
| return false; // قطعاً وجود ندارد | |
| } | |
| } | |
| return true; // احتمالاً وجود دارد | |
| } | |
| public function export(): string | |
| { | |
| // فشردهسازی برای ذخیره در دیتابیس یا فایل | |
| return gzcompress(implode('', $this->bitArray)); | |
| } | |
| public function import(string $data): void | |
| { | |
| $uncompressed = gzuncompress($data); | |
| $this->bitArray = array_map('intval', str_split($uncompressed)); | |
| } | |
| } | |
| // ---------------------------- | |
| // مثال استفاده | |
| // ---------------------------- | |
| $bf = new BloomFilter(100, 3); | |
| $bf->add('apple'); | |
| $bf->add('banana'); | |
| echo "apple? " . ($bf->mightContain('apple') ? '✅ احتمالاً وجود دارد' : '❌ ندارد') . PHP_EOL; | |
| echo "orange? " . ($bf->mightContain('orange') ? '✅ احتمالاً وجود دارد' : '❌ ندارد') . PHP_EOL; | |
| // فشردهسازی و بازیابی | |
| $compressed = $bf->export(); | |
| $newBf = new BloomFilter(100, 3); | |
| $newBf->import($compressed); | |
| echo "banana (after import)? " . ($newBf->mightContain('banana') ? '✅' : '❌') . PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment