0

I´ve an array which stores 5 inputs (int), in a guessing-game.

What I would like to do is to generate a random number (pick one of five numbers which is stored) from that array, can anyone help me with this?

I'm familliar with the rand-fuction but only to pick a random number within a range och numbers, not between 5 inputs...

funderaren
  • 19
  • 1
  • 1
  • 1

5 Answers5

6

Use e.g. std::uniform_int_distribution to get a value between 0 and 4 (inclusive) and use that as an index into the array.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
5

Assuming your array object is int arr[5] then you can use one of the following ways depending on C++ version you are using.

All versions of C++:

int random_number = arr[rand() % 5];

Keep in mind that this solution suffers from bias issues. If you want to achive good distribution of generated numbers with this way then read following answer to the same question: https://stackoverflow.com/a/6943003/1289981

Since C++11 (most correct way):

std::random_device rd;
std::default_random_engine e1(rd());
std::uniform_int_distribution<int> uniform_dist(0, 4);

int random_number = arr[uniform_dist(e1)];
Community
  • 1
  • 1
maxteneff
  • 1,523
  • 12
  • 28
  • Your first way suffers from bias issues. See [here](http://stackoverflow.com/a/6943003/3422652). – Chris Drew Oct 19 '15 at 10:25
  • @ChrisDrew you absolutly right. But it doesn't mean that this way doesn't work. This solution will produce random-generated numbers but with very bad distribution. – maxteneff Oct 19 '15 at 10:36
0

Simply use a random number generator to generate a number from 0,1,2,3,4 and use that number as index in your array, obviously.

rand is something that we typically discourage people from using, as it's not thread-safe. However, in your simple case, it should work.

Marcus Müller
  • 34,677
  • 4
  • 53
  • 94
0

You can simply generate a random number x from 0 to length of an array - 1, and then pick the x-th number from it.

Something like this:

int x = rand() % 5;

cout << inputs[x]; // here is your value
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
0

This sounds like course work so without giving you the answer directly, the logic you need to follow is-

Generate a random number that is the in the range of your input array:

0 to ( [number of inputs] - 1 )

in your case that would be 0 to 4. Make sure to store the random number into a variable e.g. a variable called randonInput

Then you select from the array using the number generated, i.e:

int randomInput = inputArray[randomNumber];

Then you will have the random input stored in the randomInput variable

anotheruser1488182
  • 315
  • 1
  • 3
  • 9