I’m making a tic tac toe game and I’m making the player’s opponent now. As you know a tic tac toe match has 9 fields, so I’ve made a vector that contains all the fields that are already used by other X’s and O’s.
std::vector<int> UsedPositions;
So before I tried getting a random value with srand(time()) and iterate through the vector to check if that position was already being used. It actually worked but it took, as you can imagine, a lot of calculations (thus time) for my poor CPU because if the vector had about 8 elements it would mean it would have to iterate 8 times (that is IF the random number is distinct, else it would have to go through it another 8 times).
TL;DR – How do I get a distinct random value that is < 10 && > 0 from a vector?
Code thats slow for me:
int FindUniqueAnswer()
{
int answer;
bool AnswerFound = false;
while(!AnswerFound)
{
bool DoesntEqual = true;
srand(time(0));
int random = rand()%10;
if(random == 0)
{
random++;
}
for(int i = 0;i<UsedPositions.size();i++)
{
if(random == UsedPositions.at(i))
{
DoesntEqual = false;
break;
}
}
if(DoesntEqual)
{
answer = random;
AnswerFound = true;
}
}
return answer;
}
Copied from cppreference.com