xxxxxxxxxx
public static readonly int RATIO_CHANCE_A = 10;
public static readonly int RATIO_CHANCE_B = 30;
// ...
public static readonly int RATIO_CHANCE_N = 60;
public static readonly int RATIO_TOTAL = RATIO_CHANCE_A
+ RATIO_CHANCE_B
// ...
+ RATIO_CHANCE_N;
Random random = new Random();
int x = random.Next(0, RATIO_TOTAL);
if ((x -= RATIO_CHANCE_A) < 0) // Test for A
{
do_something1();
}
else if ((x -= RATIO_CHANCE_B) < 0) // Test for B
{
do_something2();
}
// ... etc
else // No need for final if statement
{
do_somethingN();
}
xxxxxxxxxx
public static readonly int RATIO_CHANCE_A = 10;
public static readonly int RATIO_CHANCE_B = 30;
// ...
public static readonly int RATIO_CHANCE_N = 60;
public static readonly int RATIO_TOTAL = RATIO_CHANCE_A
+ RATIO_CHANCE_B
// ...
+ RATIO_CHANCE_N;
Random random = new Random();
int x = random.Next(0, RATIO_TOTAL);
if ((x -= RATIO_CHANCE_A) < 0) // Test for A
{
do_something1();
}
else if ((x -= RATIO_CHANCE_B) < 0) // Test for B
{
do_something2();
}
// ... etc
else // No need for final if statement
{
do_somethingN();
}
xxxxxxxxxx
private int RandWeight(List<float> weights)
{
float weightSum = 0f;
for (int i = 0; i < weights.Count; ++i)
{
weightSum += weights[i];
}
float randomValue = Random.Range(0, weightSum);
int index = 0;
float tmpSum = 0f;
while (!(tmpSum <= randomValue && (tmpSum + weights[index]) >= randomValue))
{
tmpSum += weights[index];
index++;
}
return index;
}