File tree Expand file tree Collapse file tree 1 file changed +7
-16
lines changed Expand file tree Collapse file tree 1 file changed +7
-16
lines changed Original file line number Diff line number Diff line change 1212#include < bitset>
1313#include < cmath>
1414#include < cstddef>
15+ #include < random>
1516
1617template <std::size_t N>
1718struct GenerateBitset {
18- // Construct a bitset with p*N true bits
19+ // Construct a bitset with N bits, where each bit is set with probability p.
1920 static std::bitset<N> generate (double p) {
2021 std::bitset<N> b;
2122 if (p <= 0.0 )
2223 return b;
2324 if (p >= 1.0 )
2425 return ~b;
2526
26- std::size_t num_ones = std::round (N * p);
27- if (num_ones == 0 )
28- return b;
29-
30- double step = static_cast <double >(N) / num_ones;
31- double error = 0.0 ;
27+ std::random_device rd;
28+ std::mt19937 gen (rd ());
29+ std::bernoulli_distribution d (p);
30+ for (std::size_t i = 0 ; i < N; ++i)
31+ b[i] = d (gen);
3232
33- std::size_t pos = 0 ;
34- for (std::size_t i = 0 ; i < num_ones; ++i) {
35- if (pos >= N)
36- break ;
37- b.set (pos);
38- error += step;
39- pos += std::floor (error);
40- error -= std::floor (error);
41- }
4233 return b;
4334 }
4435
You can’t perform that action at this time.
0 commit comments