Am I looking too far to see something as simple as pick a number: 0 or 1?
Random rand = new Random();
if (rand.NextDouble() == 0)
{
lnkEvents.CssClass = "selected";
}
else
{
lnkNews.CssClass = "selected";
}
Random rand = new Random();
if (rand.Next(0, 2) == 0)
lnkEvents.CssClass = "selected";
else
lnkNews.CssClass = "selected";
Random.Next picks a random integer between the lower bound (inclusive) and the upper bound (exclusive).
If you want 50/50 probability, I suggest:
Random rand = new Random();
if (rand.NextDouble() >= 0.5)
lnkEvents.CssClass = "selected";
else
lnkNews.CssClass = "selected";
It seems like what you're wanting to do (choose between two values) is more clearly expressed by using the Next method, instead of the NextDouble method.
const int ExclusiveUpperBound = 2;
if (new Random().Next(ExclusiveUpperBound) == 0)
The value produced is "greater than or equal to zero, and less than" ExclusiveUpperBound.
Random.NextDouble() will select any double number from 0 but less than 1.0. Most of these numbers are not zero, so your distribution will not be as even as you expect.
If not in a tight loop you could use
(DateTime.Now.Millisecond % 2) - double DateTime.Now.Millisecond % (double) 10) / 10
A very simple approach could be:
Random random = new Random();
bool result = random.Next(0, 2) != 0;
Then use result for your logic.
Related
I have a situation in which I must generate a random number, this number must be either zero or one
So, the code is something like this:
randomNumber = new Random().Next(0,1)
However, the business requirements state that there is just 10% probability that the generated number is zero and 90% probability that the generated number is 1
However can I include that probability in generating the random number please?
What I thought of is:
Generate array of integer that includes 10 zeros and 90 ones.
Generate a random index between 1 and 100
Take the value that corresponds to that index
But I don't know if this way is the correct way, plus, I think that C# should have something ready for it
You can implement it like that:
// Do not re-create Random! Create it once only
// The simplest implementation - not thread-save
private static Random s_Generator = new Random();
...
// you can easiliy update the margin if you want, say, 91.234%
const double margin = 90.0 / 100.0;
int result = s_Generator.NextDouble() <= margin ? 1 : 0;
to get true with a probability of 10%:
bool result = new Random().Next(1, 11) % 10 == 0;
to get true with a probability of 40%:
bool result = new Random().Next(1, 11) > 6;
First of all, you should save the reference to the random instance in order to get a proper random sequence of numbers:
Random randGen = new Random();
The second thing to know, is that the max of the random is exclusive, so to properly solve the issue you should do:
int eitherOneOrZero = randGen.Next(1, 11) % 10;
To generalize it to any variation of chances, you can do:
Random randGen = new Random();
var trueChance = 60;
int x = randGen.Next(0, 100) < trueChance ? 1 : 0;
Testing:
Random randGen = new Random();
var trueChance = 60;
var totalCount = 1000;
var trueCount = 0;
var falseCount = 0;
for (int i = 0; i < totalCount; i++)
{
int x = randGen.Next(0, 100) < trueChance ? 1 : 0;
if (x == 1)
{
trueCount++;
}
else
{
falseCount++;
}
}
Output:
True: 60.30 %
False: 39.70 %
i want to generate random number between (1 to 6),is there any way to change the chance of geting number 6 more than other numbers?
for example for this code
private void pictureBox5_MouseClick(object sender, MouseEventArgs e)
{
Random u = new Random();
m = u.Next(1,6);
label2.Text = m.ToString();
}
Let p be probability of any 1..5 numbers and 1 - p is a probability of 6:
//DONE: do not recreate Random
private static Random s_Generator = new Random();
private void pictureBox5_MouseClick(object sender, MouseEventArgs e) {
const double p = 0.1; // each 1..5 has 0.1 probability, 6 - 0.5
// we have ranges [0..p); [p..2p); [2p..3p); [3p..4p); [4p..5p); [5p..1)
// all numbers 1..5 are equal, but the last one (6)
int value = (int) (s_Generator.NexDouble() / p) + 1;
if (value > 6)
value = 6;
label2.Text = value.ToString();
}
That wouldn't be random then. If you wanted to weight it so you would get 6 half the time, you could do this:
m = u.Next(1,2);
if(m == 2)
{
label2.Text = "6";
}
else
{
label2.Text = u.Next(1,5).ToString();
}
Based on what weighting you want you could change it-> 3 instead of 2 get a 33.33% weighting and so on. Otherwise, as the commenter said, you'd have to look into probability distributions for a more mathematically elegant solution.
Depends on how more likely. An easy way (but not very flexible) would be the following:
private void pictureBox5_MouseClick(object sender, MouseEventArgs e)
{
Random u = new Random();
m = u.Next(1,7);
if (m > 6) m = 6;
label2.Text = m.ToString();
}
If you want a totally random distribution of 1...5 and just a skwed 6, then Dmitry's seems best.
If you what to skew ALL the numbers, then try this:
Create a 100 element array.
Fill it with the number 1-6 in proportions based on how often you want the number to come up. (make 33 of them 6, if you want 6 to come up 1/3rd of the time. Four 4s means it'll only come up one in 25 rolls etc. 15 or 16 of each number will make it about evenly distributed, so adjust the counts from there)
Then pick a number from 0...99 and use the value in the element of the array.
You could define the possibility in a percentage of getting each of the numbers in an array:
/*static if applicable*/
int[] p = { (int)Math.Ceiling((double)100/6), (int)Math.Floor((double)100/6), (int)Math.Ceiling((double)100/6), (int)Math.Floor((double)100/6), (int)Math.Ceiling((double)100/6), (int)Math.Ceiling((double)100/6) };
////The array of probabilities for 1 through p.Length
Random rnd = new Random();
////The random number generator
int nextPercentIndex = rnd.Next() % 100; //I can't remember if it's length or count for arrays off the top of my head
////Convert the random number into a number between 0 and 100
int TempPercent = 0;
////A temporary container for comparisons between the percents
int returnVal = 0;
////The final value
for(int i = 0; i!= p.Length; i++){
TempPercent += p[i];
////Add the new percent to the temporary percent counter
if(nextPercentIndex <= TempPercent){
returnVal = i + 1;
////And... Here is your value
break;
}
}
Hope this helps.
How can i generate different random numbers in short time?
For example:
Number = 20;
if (Number > 0)
{
AddEffect(rand.Next(0,100);
Number--;
}
In this example, rand.Next gives me twenty times the same number. Is there any way to force a change?
I think you're trying to say:
var rand = new Random();
var Number = 20;
while (Number > 0)
{
// rand.Next(0,100); // this will give 20 different numbers btw
AddEffect(rand.Next(0,100));
Number--;
}
but otherwise, seems fine
int totalNumbers = 20;
Random rand = new Random();
for (int i = 0; i < totalNumbers; i++)
{
AddEffect(rand.Next(0, 101)); // a number between -1 and 101, min: 0, max: 100
}
Is this what you mean? This is an easy and clear way to generate some random numbers.
More info here: http://www.dotnetperls.com/for
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;
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;
}
It is all in the title basically. It is simple, but I don't know why my While loop is failing sometimes. Every now and then I would get a list that is of length 2 instead of 3.
Here is my C# code:
public List<int> generateRequiredSecretCode()
{
List<int> placeHolder = new List<int>();
Random random = new Random();
int randomNo = random.Next(0, 10);
while (!placeHolder.Contains(randomNo) && placeHolder.Count != 3)
{
placeHolder.Add(randomNo);
randomNo = random.Next(0, 10);
}
return placeHolder;
}
Summary of my aim: I want a List of integers that is of length 3 and where each number in the list is between 0 and 9 and is unique
You can have a neat LINQ two-liner using
var random = new Random();
return Enumerable.Range(0,10).OrderBy(i => random.NextDouble()).Take(3).ToList();
!placeHolder.Contains(randomNo) is your problem here because the while ends if the list contains the randomNo.
Check that !placeHolder.Contains(randomNo) in an inner if like this:
while (placeHolder.Count != 3)
{
if( !placeHolder.Contains(randomNo) )
placeHolder.Add(randomNo);
randomNo = random.Next(0, 10);
}
A little late to the party, but set arithmetic seems quite elegant so couldn't resist:
private static Random RNG = new Random();
...
public static List<int> RandomNumbers() {
var numbers = new HashSet<int> { RNG.Next(0, 9), RNG.Next(0, 9), RNG.Next(0, 9) };
while (numbers.Count < 3)
{
numbers.Add(RNG.Next(0, 9));
}
return numbers.ToList();
}
It sometimes fails because, in the rare cases when Rand.Next does return an identical number to thise already in the list, !placeHolder.Contains(randomNo) will return false; false && anything = false, so the loop ends. If you'd run it long enough, you'd eventually get a list of length 1 ;)
Possible replacement:
List<int> placeHolder = new List<int>();
Random random = new Random();
int randomNo;
do {
randomNo = random.Next(0, 10);
if (!placeHolder.Contains(randomNo) && placeHolder.Count != 3)
{
placeHolder.Add(randomNo);
randomNo = random.Next(0, 10);
}
} while (placeHolder.Count < 3);
return placeHolder;
[edit]: This thread moved fast... and Animal's solution is much better than mine :(