Home > Back-end >  use percentage with c#
use percentage with c#

Time:11-29

I would like to run 3 scenarios. The first has 80% which returns IsRandom = false the other two have 10% each for Group "A" or Group "B".

Here is my code:

Random randomGen = new Random();

...

int clickPercentage = randomGen.Next(100);

if (clickPercentage <= 20 / 2)
{ 
    return new RandomGroup {IsRandom = true, Group = "A"};
}
else if (clickPercentage <= 20)
{
    return new RandomGroup { IsRandom = true, Group = "B" };
}
else
{
    return new RandomGroup { IsRandom = false };
}

Is it correct (does it provide 10% : 10% : 80% distribution)?

CodePudding user response:

Your distrubution is only roughly correct: 11% vs. 10% vs. 79%. Note, that

  • 1st option corresponds to [0..10] - 11% probability (both borders are included)
  • 2nd option corresponds to (10..20] - 10% probability (one border is included, the other is excluded)
  • The last option corresponds to (20..100) - 79% probability (both borders are excluded)

If you insist on 10% vs. 10% vs. 80% distribution put it as (your code corrected):

int clickPercentage = randomGen.Next(100);

if (clickPercentage < 10)
{ 
    return new RandomGroup {IsRandom = true, Group = "A"};
}
else if (clickPercentage < 20)
{
    return new RandomGroup { IsRandom = true, Group = "B" };
}
else
{
    return new RandomGroup { IsRandom = false };
}

Please, note < instead of <= (remember, that lower border 0 will be included when higher border 100 will be exluded)

You can simplify the code a bit with a help of turnary operator:

int clickPercentage = randomGen.Next(100);

return clickPercentage < 20 
  ? new RandomGroup() {IsRandom = true, Group = clickPercentage < 10 ? "A" : "B"} 
  : new RandomGroup { IsRandom = false };

Edit: To get rid of Resharper's complains you can drop elses which are redundant:

int clickPercentage = randomGen.Next(100);

if (clickPercentage < 10)
  return new RandomGroup {IsRandom = true, Group = "A"};
if (clickPercentage < 20)
  return new RandomGroup { IsRandom = true, Group = "B" };

return new RandomGroup { IsRandom = false };

CodePudding user response:

This

randomGen.Next(100);

returns a value between 0 and 99. So you need to either change the <= to < in your equality tests, or use randomGen.Next(1, 101) which will return a value within 1 and 100.

The former is probably better from an ease-of-understanding perspective, but really it's a matter of taste.

The division operation here is unnecessary:

if (clickPercentage <=20/2)

Simply use clickPercentage < 10

Similarly, use else if (clickPercentage < 20)

The way you instantiate RandomGroup in your else statement could be an issue depending on how the Group property is defined

  • Related