forked from Matan-Eliyahu/BookScrabble
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBloomFilter.java
More file actions
70 lines (60 loc) · 1.78 KB
/
BloomFilter.java
File metadata and controls
70 lines (60 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package test;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.BitSet;
public class BloomFilter {
BitSet bitArray;
MessageDigest[] hashFunctions;
public BloomFilter(int size, String... algNames)
{
bitArray = new BitSet(size);
hashFunctions = new MessageDigest[algNames.length];
for (int i = 0; i < hashFunctions.length; i++)
{
try
{
hashFunctions[i] = MessageDigest.getInstance(algNames[i]); //Initializing hash function by its name
}
catch (Exception e)
{
System.out.println("NoSuchAlgorithmException\n");
}
}
}
public void add(String word)
{
for (int i = 0; i < hashFunctions.length; i++)
{
//Switch the bit to 1
bitArray.set(calcIndexToSwitch(word, hashFunctions[i]));
}
}
public boolean contains(String word)
{
for (int i = 0; i < hashFunctions.length; i++)
{
//Checks if the bit is off
if (!bitArray.get(calcIndexToSwitch(word, hashFunctions[i])))
{
return false;
}
}
return true;
}
private int calcIndexToSwitch(String word, MessageDigest hashFunction)
{
byte[] bts = hashFunction.digest(word.getBytes());
BigInteger number = new BigInteger(bts);
return Math.abs(number.intValue()) % bitArray.size();
}
@Override
public String toString()
{
StringBuilder stringBitArray = new StringBuilder();
for (int i = 0; i < bitArray.length(); i++)
{
stringBitArray.append(bitArray.get(i) ? '1' : '0');
}
return stringBitArray.toString();
}
}