Reputation: 154
I'm looking to get a random int from a 2d array like this:
static const int points[6][3] = { {2,3,4}, {11,12,13}, {14,15,16}, {17,0,1}, {8,9,10}, {5,6,7} };
The output could be any number within the array.
Upvotes: 0
Views: 122
Reputation: 1420
You can use rand
from <stdlib.h>
in combination with time
from <time.h>
:
srand(time(NULL));
/* get random element */
int y = rand() % 6;
int x = rand() % 3;
int r = points[y][x];
Alternatively you could use <random>
which is preferable, as mentioned by jabaa in the comments:
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> distr(0, 5);
int y = distr(gen);
int x = distr(gen) % 3;
int r = points[y][x];
Upvotes: 1