Reputation: 1
im looking for a faster method, which allows me, to get a random number from a certain pool of numbers which are stored in an array.
I'll need the method multiple times, and the current method is terribly slowing down the code.
#include <cstdlib>
#include <ctime>
int main()
{
const int size = 8;
int numberArray[size] = { 0, 0, 3, 4, 0, 6, 7, 0 };
srand(time(0));
int rndIndex;
int rndNumber;
do
{
rndIndex = rand() % size;
rndNumber = numberArray[rndIndex];
} while (rndNumber <= 0);
}
I like to get a random number from the array, except the random number is less than 0
Upvotes: 0
Views: 620
Reputation: 3973
If I understand correctly, then you want to repeatedly pick a non-zero number from numberArray
, but the numbers in the array changes after each pick (because the knight moves to a different square with different move options). But your current solution goes slower and slower as the knight progresses, because there are more and more zeroes in the move array, making you have to loop more times before a non-zero value is picked.
One solution to this problem, that I see, is to first count the number of non-zero elements in the array. Then do a random selection (n) up to that number, and finally select the n'th non-zero number in the array. Quick code showing the idea here:
const int size = 8;
int numberArray[size] = { 0, 0, 3, 4, 0, 6, 7, 0 };
srand(time(0));
int numNonZero = 0;
for (int i = 0; i < size;++i) {
if (numberArray[i] > 0)
++numNonZero;
}
int selectionNum;
int rndNumber;
selectionNum = rand() % numNonZero;
for (int i = 0; true; ++i) {
rndNumber = numberArray[i];
if (rndNumber > 0 && selectionNum-- == 0)
break;
}
This trades a random number of loops, with a rand()
draw in each, for two loops of max 8 elements and a single rand()
draw.
BY THE WAY!
Since I am already typing this up, I am just going to mention that rand() % X
is an outdated way of generating random numbers (0 to X-1), and that STL has a better way of doing it today.
A better way would be to do something like this:
const int size = 8;
int numberArray[size] = { 0, 0, 3, 4, 0, 6, 7, 0 };
std::random_device rd;
std::mt19937 mt(rd()); // initialize the random generator
int numNonZero = 0;
for (int i = 0; i < size;++i) {
if (numberArray[i] > 0)
++numNonZero;
}
int selectionNum;
int rndNumber;
std::uniform_int_distribution<int> distribution(0, numNonZero - 1); // Set the distribution: 0 to numNonZero-1, both inclusive
selectionNum = distribution(mt); // Generate random number in the selected range
for (int i = 0; true; ++i) {
rndNumber = numberArray[i];
if (rndNumber > 0 && selectionNum-- == 0)
break;
}
You can read more here: http://www.cplusplus.com/reference/random/ or here Generate random numbers using C++11 random library
Upvotes: 1