srinath
srinath

Reputation: 2998

calculate different number when run each time

i have a multimap in which there are 1000 numbers. Now i need to generate a random number. say its 560. then i will take 560th element of an array. i used rand.

int number = 0;
int size = mmap.size();
int rand = rand() % size + 1;

but the problem is , i am running this program n times. each time, i am getting same number of random values. How to generate random values each time when i run the program.

  i tried using including random library. it gave error when i compile.

Upvotes: 0

Views: 105

Answers (3)

bames53
bames53

Reputation: 88155

In addition to seeding your random number generator, I would recommend you avoid rand() entirely, if possible. It's not usually a very good pRNG, and common usages (such as rand() % size) produce biased results. A better alternative, if available, is the standard C++ <random> library.

Some benefits of <random> over rand():

  • several engines with well defined characteristics to suit different needs.
  • predefined distributions, easier to use correctly than to produce your own.
  • well specified behavior in threaded programs.

Example:

#include <random>
#include <iostream>
#include <functional>

int main() {
    std::random_device r;
    std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};
    std::mt19937 e(seed);

    int size = 10;
    std::uniform_int_distribution d(1,size);

    std::cout << d(e) << '\n';
}

You can also bind everything up into a single function object, if that suits your usage better.

#include <functional>

std::random_device r;
std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};

auto rand = std::bind(std::uniform_int_distribution<>(1,size),
                      std::mt19937(seed));
std::cout << rand() << '\n';

Upvotes: 1

MrLeap
MrLeap

Reputation: 506

You need to seed your random number with something. Try srand (time(NULL));

Upvotes: 4

user1944441
user1944441

Reputation:

You forgot srand.

srand(time(NULL))

Add this at the beginning of your code. you only have to call it once. It will seed based on current time. Since you have time(NULL) in there you have to include time.h

Upvotes: 8

Related Questions