【資料結構】點陣圖與布隆處理器
阿新 • • 發佈:2018-11-25
文章目錄
1.點陣圖的實現
BitMap.h
#ifndef __BITSET_H__ #define __BITSET_H__ #include<stdio.h> #include<stdlib.h> #include<assert.h> #include<string.h> typedef struct BitSet { char* a; size_t N;//開闢的位個數 }BitSet; void BitSetInit(BitSet* p, size_t n); void BitSetDestory(BitSet* p); //置1 void BitSetSet1(BitSet* p, size_t x); //把1變為0 void BitSetSet0(BitSet* p, size_t x); //判斷數字是否在 int HaveNumber(BitSet* p, size_t x); #endif
BitMap.c
#include "BitSet.h" void BitSetInit(BitSet* p, size_t n) { assert(p); p->N = n; //確定需要的位元組數,並且+1,比如33/8應該是5個位元組 size_t size = (n >> 3) + 1; //動態開闢 p->a = (char*)malloc(size); //初始化 memset(p->a, 0, size); } void BitSetDestory(BitSet* p) { assert(p); free(p->a); p->a = NULL; p->N = 0; } void BitSetSet1(BitSet* p, size_t x) { assert(p); //計算在第幾個char中 int index = x >> 3; //第幾位 int num = x % 8; p->a[index] |= (1 << num); } void BitSetSet0(BitSet* p, size_t x) { assert(p); int index = x >> 3; int num = x % 8; p->a[index] &= ~(1 << num); } //判斷數字是否存在 int HaveNumber(BitSet* p, size_t x) { assert(p); int index = x >> 3; int num = x % 8; int ret = p->a[index] & (1 << num); if (0 == ret) return 0; else return 1; }
2.布隆的實現
BloomFilter.h
#ifndef __BLOOMFITER_H__ #define __BLOOMFILTER_H__ #include"BitSet.h" typedef struct BloomFilter { BitSet b; }BloomFilter; void BloomFilterInit(BloomFilter* p,size_t n); void BloomFilterDestory(BloomFilter* p); void BloomFilterSet1(BloomFilter* p, char* x); int BloomFilterHaveNumber(BloomFilter* p, char* x); #endif
BloomFilter.c
#include"BloomFilter.h"
size_t HashFunc1(char* p)
{
assert(p);
size_t hash = 0;
while (*p)
{
hash = hash * 131 + (size_t)*p;
p++;
}
return hash;
}
size_t HashFunc2(char* p)
{
assert(p);
size_t hash = 0;
while (*p)
{
hash = hash * 31 + (size_t)*p;
p++;
}
return hash;
}
size_t HashFunc3(char* p)
{
assert(p);
size_t hash = 0;
while (*p)
{
hash = hash * 1313 + (size_t)*p;
p++;
}
return hash;
}
void BloomFilterInit(BloomFilter* p ,size_t n)
{
assert(p);
BitSetInit(&(p->b),n );
}
void BloomFilterDestory(BloomFilter* p)
{
assert(p);
BitSetDestory(&(p->b));
}
void BloomFilterSet1(BloomFilter* p, char* x)
{
assert(p);
size_t index1 = HashFunc1(x);
size_t index2 = HashFunc2(x);
size_t index3 = HashFunc3(x);
BitSetSet1(&(p->b), index1);
BitSetSet1(&(p->b), index2);
BitSetSet1(&(p->b), index3);
}
int BloomFilterHaveNumber(BloomFilter* p, char* x)
{
assert(p);
size_t index1 = HashFunc1(x);
if (HaveNumber(&(p->b), index1))
{
size_t index2 = HashFunc2(x);
if (HaveNumber(&(p->b), index2))
{
size_t index3 = HashFunc3(x);
if (HaveNumber(&(p->b), index3))
{
return 1;
}
}
}
return 0;
}