0

Could someone please point me to a good explanation of how this might be accomplished?

For example, let's say I have an array a[j] initialized to the values {3, 4, 5}. I want to build a second array filled with random numbers bounded below by zero and above by the values in the first array. So b[i] would be initialized to a random number in the following ranges: {0-3, 0-4, 0-5}

What is a good way of achieving this in C++?

Victor Brunell
  • 5,668
  • 10
  • 30
  • 46

2 Answers2

1

If your system has arc4random(3) and friends (and it probably does), it's really easy:

int a[3] = {3, 4, 5};
int b[3];
for (int i = 0; i < 3; i++)
{
    b[i] = arc4random_uniform(a[i] + 1);
} 

From the manual page linked above:

arc4random_uniform() will return a single 32-bit value, uniformly distributed but less than upper_bound.

Community
  • 1
  • 1
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
0

The most common function in c++ is the function rand() which generates a random numer between 0 and RAND_MAX which is defined in cstdlib. That is why you need to use the modulo operation, in your case it would be:

b[i] = rand() % (a[i]+1)
Albondi
  • 1,141
  • 1
  • 8
  • 19
  • Watch out for [modulo bias](http://stackoverflow.com/questions/10984974/why-do-people-say-there-is-modulo-bias-when-using-a-random-number-generator) if that might be a problem for your program. – Carl Norum Apr 08 '15 at 00:47