Multiple Percent Chance

Hey there, if they are mapped 1:1 then you should probably use a map of objects and float instead of 2 arrays, because that will ensure the relationship. When you search for an object it will have its corresponding chance.

Say that I have an array of objects and each has a chance of being chosen, how do I make sure it is selecting them at the correct percentage chance.

0: 5% chance
1: 12% chance
2: 0.1% chance
3: 82.9% chance

I know there is random bool with weight but won’t the booleans generated conflict?

I am using an array of structs with the chance values.

Can you show me the struct?

Ok i belive i understand your question now. The first thing that comes into my mind is this:

float ProbSubtraction = 100;
const float Random = FMath::FRandRange(0, 100);   // Randomize a number between 0 and 100

for (int32 i = 0 ; i < Items.Num() ; i++)  // Loop through all of the items
	ProbSubtraction = ProbSubtraction -  Items[i].Chance; // Subtract the chance

	if (Random >= ProbSubtraction )   // Check if the random number is bigger or equal than the subtraction, if it is then that is your item.
		//Do stuff with your selected item

		break;    // You need to break the for loop here, or else you'll get the rest of the items as the right one.

The overall idea is to have a float variable starting at 100 and then you loop through your items array and you keep subtracting the chance and if the random number is bigger or equal to your current subtraction then that’s your item.

Hi! I see xlar8or gave you a correct answer but since I see you are asking help in BP sections I want to be sure you can own something :slight_smile:

This one is a function that receive in input an array of chances and return in output a random integer that is the index corresponding to the randomly chosen array element considering the array element as the probability of being chosen.

This function works even if the sum of all elements isn’t 100.

Also, putting it in a function library you can call it whenever you want (remember to set the function pure).

You can use each type of number variable (short, int, float) but you need to create a new function for each one. Maybe you can make an universal one with a macro but I wouldn’t bet on it :smiley:

Have a nice day!

Is there anything that I need to do different with float because it keeps evaluating to the first item in the array.

Hi, sorry, it return 0 because I’ve done 2 mistakes writing the BP, my fault! Here’s the fix: