Skip to content
This repository has been archived by the owner on Jul 7, 2020. It is now read-only.

Commit

Permalink
Add support for intersection to BloomFilter.
Browse files Browse the repository at this point in the history
  • Loading branch information
b4hand committed May 30, 2017
1 parent 7e38ed9 commit 5620c2c
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,27 @@ public Filter merge(Filter... filters) {
return merged;
}

public void intersectInPlace(BloomFilter other) {
if (this.getHashCount() != other.getHashCount()) {
throw new IllegalArgumentException("Cannot intersect filters of different sizes");
}
this.filter().and(other.filter());
}

public BloomFilter intersect(BloomFilter... filters) {
BloomFilter intersected = new BloomFilter(this.getHashCount(), (BitSet) this.filter().clone());

if (filters == null) {
return intersected;
}

for (BloomFilter filter : filters) {
intersected.intersectInPlace(filter);
}

return intersected;
}

/**
* @return a BloomFilter that always returns a positive match, for testing
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,54 @@ public void testMergeException() {
BloomFilter mergeBf = (BloomFilter) bf3.merge(bf);
}

@Test
public void testIntersectInPlace() {
BloomFilter bf3 = new BloomFilter(ELEMENTS, spec.bucketsPerElement);
for (int i = 0; i < 20; ++i) {
bf.add(Integer.toString(i));
}
for (int i = 10; i < 30; ++i) {
bf2.add(Integer.toString(i));
}
for (int i = 10; i < 20; ++i) {
bf3.add(Integer.toString(i));
}
bf.intersectInPlace(bf2);
for (int i = 0; i < 30; ++i) {
String iString = Integer.toString(i);
if (bf3.isPresent(iString)) {
assertTrue(bf.isPresent(iString));
} else {
assertFalse(bf.isPresent(iString));
}
}
}

@Test(expected=IllegalArgumentException.class)
public void testIntersectInPlaceException() {
BloomFilter bf3 = new BloomFilter(ELEMENTS*10, 1);
bf3.intersectInPlace(bf);
}

@Test
public void testIntersect() {
for (int i = 0; i < 20; ++i) {
bf.add(Integer.toString(i));
}
for (int i = 10; i < 30; ++i) {
bf2.add(Integer.toString(i));
}
BloomFilter bf3 = bf.intersect(bf2);
for (int i = 0; i < 30; ++i) {
String iString = Integer.toString(i);
if (bf.isPresent(iString) && bf2.isPresent(iString)) {
assertTrue(bf3.isPresent(iString));
} else {
assertFalse(bf3.isPresent(iString));
}
}
}

@Test
public void testFalsePositivesInt() {
FilterTest.testFalsePositives(bf, FilterTest.intKeys(), FilterTest.randomKeys2());
Expand Down

0 comments on commit 5620c2c

Please sign in to comment.