-
Notifications
You must be signed in to change notification settings - Fork 70
Description
public static string flip() {
if (Math.random() > 0.33) {
return "head";
}
else {
return "tails";
}
}
I might be too nit picky at this point, but "head" should be "heads"'. Also, This method returns heads slightly more than twice that of tails, as 0.33 * 3 is 0.99, meaning heads is returned 67/100 of the time while tails is returned 33/100 of the time. 33*2 = 66, not 67.
The correct version:
public static string flip() {
int chance = (int)(Math.Random() * 3);
if (chance == 0)
return "tails";
return "heads";
}
The reason this works better, is there is exactly a 2/3 chance to get heads, and 1/3 to get tails. Math.Random*3 gets a number between 0 and 2.999999999999(I'd keep going but i think you get the point), and concatenates the decimal part of in the (int) conversion, so 2.98 would be just 2, and would return heads. return "heads"; does not have to be in the if statement, because it will only be executed if return "tails"; is not. You can always sub in "chance == 1" or "chance == 2" for "chance == 0", and still get the same result.