Question

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

Était-ce utile?

La solution

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 }.

Autres conseils

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;

Here is my implementation. Similar to the above but slightly different. Figure more answers could help you out even more.

    public int result()
    {
        // randomly generate a number either 1 or -1
        int i;
        Random rando = new Random();
        i = rando.Next(0, 2);
        if (i == 0)
        {
            i = -1;
        }
        return i;
    }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top