Philly
Philly

Reputation: 13

Print a random number from my own array

I've been trying to understand how to print out some random numbers from my own array, dont confuse this with that i want to generate random numbers into an array, which is not what im trying to accomplish. However, my code is like this

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
srand(time(NULL));
int myarray[] = { 2, 5, 10 };   
//Its here where i dont know how to use rand() in to make the program generate one random number from my array, either 2, 5 or 10. I've tried, but failed.

return 0;
}

Ive not found any similar question to this either, so would greatly appreciate some help.

Upvotes: 0

Views: 76

Answers (3)

PandaConda
PandaConda

Reputation: 3506

You can use the following formula to generate a random number within a range:

rnd(min, max) = (rand() % (max - min)) + min;

In your case you, min = 0 and max = 3, which gives you rand() % 3.

Upvotes: 2

Jeremy
Jeremy

Reputation: 576

The other answers use rand() % 3 for generating a (pseudo-)"random" number between 0 and 2 (including both). This might work for you, but is not really random, since the numbers returned by rand() between RAND_MIN and RAND_MAX are not distributed uniformly in terms of their divisibility through a given number n (because the equivalence classes of the modulo relation have unequal amounts of members if RAND_MAX is not a multiple of n).

A better algorithm for getting (pseudo-)random numbers in a given range is:

int RangeRandom(int min, int max) {
    int n = max - min + 1;
    int remainder = RAND_MAX % n;
    int x;
    do
    {
        x = rand();
    } while (x >= RAND_MAX - remainder);
    return min + x % n;
}

You can then use the function RangeRandom as follows:

int myArray[] = { 0, 3, 5 };
printf("%d", myArray[RangeRandom(0, 2)]);

Upvotes: 0

Hatted Rooster
Hatted Rooster

Reputation: 36463

int number = myarray[rand() % 3];

This generates a random number : 0 1 2 and then accesses that element from the array.

Upvotes: 3

Related Questions