am d4dbbd50: Use C++11 random library

* commit 'd4dbbd5008438855c56e38eba9c0ee1368a53a5a':
  Use C++11 random library
main
Yohei Yukawa 2014-04-09 09:32:23 +00:00 committed by Android Git Automerger
commit 807c4b652d
1 changed files with 30 additions and 11 deletions

View File

@ -18,8 +18,10 @@
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include <algorithm>
#include <cstdlib> #include <cstdlib>
#include <ctime> #include <functional>
#include <random>
#include <unordered_set> #include <unordered_set>
#include <vector> #include <vector>
@ -27,32 +29,49 @@ namespace latinime {
namespace { namespace {
TEST(BloomFilterTest, TestFilter) { TEST(BloomFilterTest, TestFilter) {
static const int TEST_RANDOM_DATA_MAX = 65536;
static const int ELEMENT_COUNT = 1000; static const int ELEMENT_COUNT = 1000;
srand(time(0));
std::vector<int> elements; std::vector<int> elements;
std::unordered_set<int> elementsThatHaveBeenSetInFilter;
for (int i = 0; i < ELEMENT_COUNT; ++i) { // Initialize data set with random integers.
elements.push_back(rand()); {
// Use the uniform integer distribution [0, TEST_RANDOM_DATA_MAX].
std::uniform_int_distribution<int> distribution(0, TEST_RANDOM_DATA_MAX);
auto randomNumberGenerator = std::bind(distribution, std::mt19937());
for (int i = 0; i < ELEMENT_COUNT; ++i) {
elements.push_back(randomNumberGenerator());
}
} }
// Make sure BloomFilter contains nothing by default.
BloomFilter bloomFilter; BloomFilter bloomFilter;
for (const int elem : elements) { for (const int elem : elements) {
ASSERT_FALSE(bloomFilter.isInFilter(elem)); ASSERT_FALSE(bloomFilter.isInFilter(elem));
} }
for (const int elem : elements) {
if (rand() % 2 == 0) { // Copy some of the test vector into bloom filter.
bloomFilter.setInFilter(elem); std::unordered_set<int> elementsThatHaveBeenSetInFilter;
elementsThatHaveBeenSetInFilter.insert(elem); {
// Use the uniform integer distribution [0, 1].
std::uniform_int_distribution<int> distribution(0, 1);
auto randomBitGenerator = std::bind(distribution, std::mt19937());
for (const int elem : elements) {
if (randomBitGenerator() == 0) {
bloomFilter.setInFilter(elem);
elementsThatHaveBeenSetInFilter.insert(elem);
}
} }
} }
for (const int elem : elements) { for (const int elem : elements) {
const bool existsInFilter = bloomFilter.isInFilter(elem); const bool existsInFilter = bloomFilter.isInFilter(elem);
const bool hasBeenSetInFilter = const bool hasBeenSetInFilter =
elementsThatHaveBeenSetInFilter.find(elem) != elementsThatHaveBeenSetInFilter.end(); elementsThatHaveBeenSetInFilter.find(elem) != elementsThatHaveBeenSetInFilter.end();
if (hasBeenSetInFilter) { if (hasBeenSetInFilter) {
ASSERT_TRUE(existsInFilter); EXPECT_TRUE(existsInFilter) << "elem: " << elem;
} }
if (!existsInFilter) { if (!existsInFilter) {
ASSERT_FALSE(hasBeenSetInFilter); EXPECT_FALSE(hasBeenSetInFilter) << "elem: " << elem;
} }
} }
} }