How would I go about using a random number generator to generate either 1 or -1 but not 0. I have so far: xFacingDirection = randomise.Next(-1,2);
but that runs the risk of generating the number 0. How would I go about making not accept 0 or keeping trying for a number until its not 0.
Many thanks
What about this:
var result = random.Next(0, 2) * 2 - 1;
To explain this, random.Next(0, 2)
can only produce a value of 0 or 1. When you multiply that by 2, it gives either 0 or 2. And simply subtract 1 to get either -1 or 1.
In general, to randomly produce one of n integers, evenly distributed between a minimum value of x and a maximum value of y, inclusive, you can use this formula:
var result = random.Next(0, n) * (y - x) / (n - 1) + x;
For example substituting n=4, x=10, and y=1 will generate randum numbers in the set { 1, 4, 7, 10 }.
You could also use a ternary operator to determine which number to use.
int number = (random.Next(0, 2) == 1) ? 1 : -1);
It evaluates to
if (random.Next(0, 2) == 1)
number = 1;
else
number = -1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With