OLD | NEW |
---|---|
(Empty) | |
1 // Copyright 2015 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 #ifndef CHROME_BROWSER_METRICS_PERF_RANDOM_SELECTOR_H_ | |
6 #define CHROME_BROWSER_METRICS_PERF_RANDOM_SELECTOR_H_ | |
7 | |
8 #include <string> | |
9 #include <vector> | |
10 | |
11 #include "base/macros.h" | |
12 | |
13 // RandomSelector can be used to pick vectors of strings according to certain | |
14 // probabilities. The probabilities are set using SetOdds(). A randomly picked | |
15 // vector can be obtained by calling Select(). | |
16 // | |
17 // Sample usage: | |
18 // | |
19 // RandomSelector random_selector; | |
20 // std::vector<RandomSelector::WeightAndValue> odds { | |
21 // {50, "a"}, | |
22 // {40, "b"}, | |
23 // {10, "c"} | |
24 // }; | |
25 // random_selector.SetOdds(odds); | |
26 // | |
27 // // The following should return "a" with a probability of 50%, | |
28 // // "b" with a probability of 40%, and "c" with a probability of 10%: | |
29 // | |
30 // std::vector<std::string>& selection = random_selector.Select(); | |
31 class RandomSelector { | |
32 public: | |
33 struct WeightAndValue { | |
34 WeightAndValue(double weight, const std::string& value) | |
35 : weight(weight), value(value) { | |
36 } | |
37 | |
38 double weight; | |
39 std::string value; | |
40 }; | |
41 | |
42 RandomSelector(); | |
43 virtual ~RandomSelector(); | |
44 | |
45 // Set the probabilities for various strings. | |
46 void SetOdds(const std::vector<WeightAndValue>& odds); | |
47 | |
48 // Get the next randomly picked string. | |
Alexei Svitkine (slow)
2015/09/15 15:31:18
Nit: Update comment (don't use the term "next" sin
dhsharp
2015/09/15 18:21:32
Done.
| |
49 const std::string& Select(); | |
50 | |
51 // Returns the number of string entries. | |
52 size_t num_values() const { | |
53 return odds_.size(); | |
54 } | |
55 | |
56 // Sum of the |weight| fields in the vector. | |
57 static double SumWeights(const std::vector<WeightAndValue>& odds); | |
58 | |
59 private: | |
60 // Get a floating point number between 0.0 and |max|. | |
61 virtual double RandDoubleUpTo(double max); | |
62 | |
63 // Get a string corresponding to |random| that is in the odds vector. | |
64 // |random| must be a number between zero and the sum of the probability | |
65 // weights. | |
66 const std::string& GetValueFor(double random); | |
67 | |
68 // A dictionary representing the strings to choose from and associated odds. | |
69 std::vector<WeightAndValue> odds_; | |
70 | |
71 double sum_of_odds_; | |
Alexei Svitkine (slow)
2015/09/15 15:31:18
Nit: Add a comment.
dhsharp
2015/09/15 18:21:32
Done.
| |
72 | |
73 DISALLOW_COPY_AND_ASSIGN(RandomSelector); | |
74 }; | |
75 | |
76 #endif // CHROME_BROWSER_METRICS_PERF_RANDOM_SELECTOR_H_ | |
OLD | NEW |