Answer the question
In order to leave comments, you need to log in
Random random with a chance coefficient, how to do?
Hello.
I'm working on one script in the game, but I don't understand how to do it right, because I'm very weak in C ++. Tell me please.
The bottom line is this: there is a script for an action in which one of several items should be issued. But at the same time, each of these items has a different chance of falling out.
I thought of making it a very simple option without a chance coefficient.
override void ChanceItemDrop()
{
string itemsRandom[] = {
"a", "b", "c", "d", "e"
};
int min = 0;
int max = 5;
int intRandom = Math.RandomInt(min, max); // Получаем случайное число от 0 до 5
string randItems = itemsRandom[intRandom]; // Получаем предмет из массива "itemsRandom" с помощью рандома "intRandom"
if(randItems == "a"){
// Выдаём a
}else if(randItems == "b"){
// Выдаём b
}else if(randItems == "c"){
// Выдаём c
}else if(randItems == "d"){
// Выдаём d
}else{
// Выдаём предмет (e)
}
// Здесь я выдаю предмет
}
Answer the question
In order to leave comments, you need to log in
And it works vprinitspi. How can I make it possible for each item to have a specific drop rate? Or at least tell me where to dig, in what direction.
Can it be like this
double getRand(){//возвращает рандом от 0 до 1
return (double)rand()/(double)RAND_MAX;
}
string ChanceItemDrop(){
string itemsRandom[] = {
"a", "b", "c", "d", "e"
};
float itemsChance[] = {
.30f, .80f, .50f, .30f, .40f //шансы от 0 до 1, 1 -100% , 0 - 0%
};
int arrLen = sizeof(itemsChance)/sizeof(*itemsChance);
double r;
int arrSize;
do{
r = getRand();
arrSize = 0;
for(int i=0;i < arrLen;i++)
arrSize += r <= itemsChance[i]?1:0;
}while(arrSize == 0);
int* inxs= new int[arrSize];
for(int i=0,p = 0;i < arrLen;i++)
if(r <= itemsChance[i])
inxs[p++] = i;
string result = itemsRandom[inxs[(int)floor(getRand()*arrSize)]];
free(inxs);
return result;
}
float number = ((float) rand()) / MAX_RAND; // число от 0.0 до 1.0
if (number > 0.9)
cout << "yes" << endl;
else
cout << "no" << endl;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question