0

I am using the boost/random.hpp to fill a std::map with random numbers on the interval [1,3] and have kind of thrown together something that will give me the % of each count in relation to the total amount of generated numbers but was looking for a maybe a more efficient way of doing it. I have been trying to find something in the boost library but am having trouble finding something completely relevant; is there something in boost that can use my map (I don't want to change my map types) and calculate the %'s or anything else I should consider?

int main()
 {
    std::map <int, long> results;
    int current;
    long one = 0;
    long two = 0;
    long three = 0;
    long total = 0;

    boost::random::mt19937 rng;
    rng.seed(static_cast<boost::uint32_t> (std::time(0)));
    boost::random::uniform_int_distribution<int> random(1,3);

    for (int n = 0; n < 1000000; ++n)
    {
        current = random(rng);
        ++total;

        switch (current)
        {
            case 1:
                ++one;
                break;
            case 2:
                ++two;
                break;
            case 3:
                ++three;
                break;
        }
    }

    results[1] = one;
    results[2] = two;
    results[3] = three;

    std::cout << (double) results[1]/total*100 << std::endl; // etc.
}

edit: I don't want to change the map container in any way.

1

3 Answers 3

3

You say you don't want to change the map type, but I don't see much reason to use a map at all for this job. It seems like the obvious choice would be a vector:

static const unsigned total = 1000000;

std::vector<unsigned> values(3);

for (int i=0; i<total; i++)
    ++values[random(rng)-1];

for (int i=0; i<values.size(); i++)
    std::cout << (values[i] * 100.0) / total;
2

Why don't you profile it? There is no point in optimizing the percentage part until you know how it impacts the speed of the program as a whole. For example, if the percentage part takes only 1% of the time of the program (most being spent in random number generation) then even doubling the efficiency would increase the speed by only .5%.

1

Efficient? Discard the map and declare results as an array of 4 elements: int results[4] = {0};, and instead of using switch/case you can directly do ++results[current].

1
  • I don't want to change the map<int, long> part. Is there anything I can do outside of the map<int, long>?
    – bqui56
    Feb 12, 2012 at 14:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.