Test the behavior of weighted shuffle by ensuring that the probability distribution after a number of runs is within a particular error bound.
| 55 | // probability distribution after a number of runs is within |
| 56 | // a particular error bound. |
| 57 | TEST(WeightedShuffleTest, ProbabilityDistribution) |
| 58 | { |
| 59 | std::mt19937 generator(0); // Pass a consistent seed. |
| 60 | |
| 61 | // Count of how many times item i was shuffled into position j. |
| 62 | size_t totalRuns = 1000u; |
| 63 | size_t counts[5][5] = {}; |
| 64 | |
| 65 | for (size_t run = 0; run < totalRuns; ++run) { |
| 66 | // Items: [ 0, ..., 4] |
| 67 | // Weights: [1.0, ..., 5.0] |
| 68 | vector<size_t> items = {0, 1, 2, 3, 4}; |
| 69 | vector<double> weights = {1.0, 2.0, 3.0, 4.0, 5.0}; |
| 70 | |
| 71 | mesos::internal::master::allocator::weightedShuffle( |
| 72 | items.begin(), items.end(), weights, generator); |
| 73 | |
| 74 | for (size_t i = 0; i < items.size(); ++i) { |
| 75 | // Count the item landing in position i. |
| 76 | ++counts[items[i]][i]; |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | // This table was generated by running a weighted shuffle algorithm |
| 81 | // for a large number of iterations. |
| 82 | double expectedProbabilities[5][5] = { |
| 83 | { 0.07, 0.08, 0.12, 0.20, 0.54 }, |
| 84 | { 0.13, 0.16, 0.20, 0.28, 0.23 }, |
| 85 | { 0.20, 0.22, 0.24, 0.22, 0.12 }, |
| 86 | { 0.27, 0.26, 0.23, 0.17, 0.07 }, |
| 87 | { 0.33, 0.28, 0.21, 0.13, 0.04 }, |
| 88 | }; |
| 89 | |
| 90 | double actualProbabilities[5][5]; |
| 91 | |
| 92 | for (int i = 0; i < 5; ++i) { |
| 93 | for (int j = 0; j < 5; ++j) { |
| 94 | actualProbabilities[i][j] = counts[i][j] / (1.0 * totalRuns); |
| 95 | |
| 96 | // Assert that the actual probabilities differ less than |
| 97 | // an absolute 5%. |
| 98 | ASSERT_NEAR(expectedProbabilities[i][j], actualProbabilities[i][j], 0.05); |
| 99 | } |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | |
| 104 | // Test the behavior of the random sorter by ensuring that the |
nothing calls this directly
no test coverage detected