Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Random Number Generator -1 or 1 only?

Tags:

c#

random

numbers

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

like image 855
Tom Carter Avatar asked Apr 29 '14 00:04

Tom Carter


2 Answers

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

like image 115
p.s.w.g Avatar answered Oct 07 '22 03:10

p.s.w.g


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;
like image 24
Liam McInroy Avatar answered Oct 07 '22 01:10

Liam McInroy