C# Code only works when using the debugger? [duplicate] - c#

This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 7 years ago.
So here's the code I've been using. Its just a simple program to test to see if 3 randomly generated numbers are in ascending or descending order. For some reason if I'm using the debugger and stepping into every line then the code works properly. If not then it says the numbers are in order 100% or out of order 100%, which should not be the case.
Here is the code I've been using:
int num1;
int num2;
int num3;
int yes = 0;
int no = 0;
for (int i = 0; i <= 99; i++)
{
Random rnd = new Random();
num1 = rnd.Next(1, 11);
num2 = rnd.Next(1, 11);
num3 = rnd.Next(1, 11);
if ( ((num1 <= num2) && (num2 <= num3)) || ((num1 >= num2) && (num2 >= num3)) )
{
yes += 1;
}
else
{
no += 1;
}
}
Console.WriteLine("The Number are in ascending order " + yes.ToString() + " Times");
Console.WriteLine("The Number are not in ascending order " + no.ToString() + " Times");
Console.ReadLine();
I think that it might be a problem with the pseudo random and the code generating the same 3 numbers every time, but I'm still learning more about programming and other help would be greatly appreciated.

The new Random() constructor uses the current time as the seed.
Unless you wait in the debugger, all of your Random instances have the same seed.
You should use a single instance.

This has to do with how the random numbers are generated.
If you take
Random rnd = new Random();
and move it out of the loop, you should see the desired results.
More background:
The random number generator uses a seed based on the time you instantiate it. Because your code is running so quickly, the seed is the same so the numbers are the same. This is why it works when you step through.
Instantiating the Random outside of the loop will instantiate it once and use the random algorithm to generate new numbers.

Related

C# Generating a random number in while loop [duplicate]

This question already has answers here:
How do I generate a random integer in C#?
(31 answers)
Closed 5 years ago.
I've tried everything from YouTube videos to this forum.
I used to find always a solution here but now I'm stuck.
I need to generate a random number between 39 and 52.
Here's the somewhat source:
case Form1.number.WITHRANDOM:
{
int i = 0;
while (i < ammount)
{
i++;
int j = 0;
string text2 = "";
while (j < 2)
{
string value = Conversions.ToString(this.random.Next(0, text.Length));
text2 += Conversions.ToString(text[Conversions.ToInteger(value)]);
j++;
}
this.numberList.Add("173" + (The random number) + text2);
}
break;
}
You should use the Random class. Its Next method returns a random integer within a specified range (between minValue and maxValue):
public virtual int Next(int minValue, int maxValue)
So, in your case, this is the code:
Random random = new Random();
int number = random.Next(39, 52);

Making a dice game [duplicate]

This question already has answers here:
How to let the user enter any amount of variable from Console
(3 answers)
Closed 7 years ago.
I am trying to learn C# on my own. I wanted to make a dice game that lets the user enter any number of dice that he or she wants. So if the user enters 10 dice, 10 list of the dice roll would appear next to each other. Here is where I can't figure it out. How can I let the user input any number of dice he or she wants? It would be impractical to use an array or list because I have to give each section of the 10 times or more. It would be nice to give a simple example.
static void Main(string[] args)
{
Random numbergen = new Random();
int dice1=0;
int dice2=1;
for (int counter = 0; counter <= 1; counter++)
{
while (dice1 != dice2)
{
dice1 = numbergen.Next(1, 7);
dice2 = numbergen.Next(1, 7);
if (dice1 == dice2)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(dice1 + "\t" + dice2);
counter++;
dice1 = 0;
dice2 = 1;
}
else if (dice1 != dice2)
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(dice1 + "\t" + dice2);
}
if (counter ==1 )
{
break;
}
}
}
Console.ReadLine();
}
Most likely, you want a List<>, something like this:
int size = 10; // Or user input
List<int> dice = new List<int>(size);
The form of the constructor that takes an Int32 argument pre-allocates that many items in the list.
Then, rather than dice1 = numbergen.Next(1, 7);, you have dice[0] = ....
You'll obviously need a loop to generate the values and decide how you want to interpret your condition of two of them being equal (which will probably also require a loop of some sort), but if I'm understanding the question correctly, this should get you going.
(You can do something similar with an array, but lists are handy in other ways, as you can see from the first link.)
Alternatively, instead of pre-allocating and filling them in separately, you can allocate an empty list and then fill your items in with something more like:
int size = 10;
for (int i = 0; i < size; i++) {
dice.Add(numbergen.Next(1, 7));
}
That's probably preferred by most people, but the difference should be pretty much negligible for this sort of work.
(And while you're at it, change your for loop to a while and change counter to a bool with a more useful name...)

Non duplicate random numbers in C# [duplicate]

This question already has answers here:
Random.Next returns always the same values [duplicate]
(4 answers)
Closed 9 years ago.
I am trying to create a range of non duplicate random numbers between 1 - 10, I planned on doing this by storing each random number I made in to an array and then checking that array every time to make sure I ain't already used the number.
My problem is that instead of creating different random numbers such as 1, 2, 3 I just keep getting the same random number over and over.
randomNumber();
Label1.Text = randomRow + "";
randomNumber();
Label2.Text = randomRow + "";
randomNumber();
Label3.Text = randomRow + "";
public int randomNumber()
{
List<int> numbers = new List<int>();
int num = 0;
Random randNum = new Random();
num = randNum.Next(1, 11);
if (numbers.Contains(num))
{
num = randNum.Next(1, 11);
}
else
{
randomRow = num;
numbers.Add(num);
}
return randomRow;
}
Problem : everytime you are creating the RandomNumber object in too close time.
When you create a Random object, it's seeded with a value from the system clock. If you create Random instances too close in time, they will all be seeded with the same random sequence.
From Here
When you create a Random object, it's seeded with a value from the
system clock. If you create Random instances too close in time, they
will all be seeded with the same random sequence.
Solution :
move Random randNum = new Random(); outside the function randomNumber().
Try This:
Random randNum = new Random();
public int randomNumber()
{
List<int> numbers = new List<int>();
int num = 0;
num = randNum.Next(1, 11);
if (numbers.Contains(num))
{
num = randNum.Next(1, 11);
}
else
{
randomRow = num;
numbers.Add(num);
}
return randomRow;
}
My best gues is that you are using this in a loop. In this case because you declare
Random randNum = new Random();
evry time this will generate tha same number. Just declare it BEFORE the loop and it should be fine.
Also you should consider a different approch because it is not a good practice. Like:
int[] array = {1,2,3,4,5,6,7,8,9,10};
Random randNum = new Random();
int rand=0;
int temp;
for(int i = 0; i<10;i++)
{
rand = randNum.next(1,10-i);
temp=array[rand];
array[rand]=array[9-i];
array[9-i]=temp;
}

Percentage Based Probability

I have this code snippet:
Random rand = new Random();
int chance = rand.Next(1, 101);
if (chance <= 25) // probability of 25%
{
Console.WriteLine("You win");
}
else
{
Console.WriteLine("You lose");
}
My question is, does it really calculate a 25% probability for winning here?
Is the chance of winning for the player here is really 25%?
Edit:
I just wrote this:
double total = 0;
double prob = 0;
Random rnd = new Random();
for (int i = 0; i < 100; i++)
{
double chance = rnd.Next(1, 101);
if (chance <= 25) prob++;
total++;
}
Console.WriteLine(prob / total);
Console.ReadKey();
And it's highly inaccurate. It goes from about 0.15 to 0.3.
But when I do more checks (change from (i < 100) to (i < 10000)) it's much more accurate.
Why is this? Why aren't 100 checks enough for it to be accurate?
This is very easy to check for yourself:
Random rand = new Random();
int yes = 0;
const int iterations = 10000000;
for (int i = 0; i < iterations; i++)
{
if (rand.Next(1, 101) <= 25)
{
yes++;
}
}
Console.WriteLine((float)yes/iterations);
the result:
0.2497914
The conslusion: Yes, yes it is.
Edit: Just for fun, the LINQy version:
Random rand = new Random();
const int iterations = 10000000;
int sum = Enumerable.Range(1, iterations)
.Count(i => rand.Next(1, 101) <= 25);
Console.WriteLine(sum / (float)iterations);
For most cases, I would say yes. However, you have to remember that most randomization algorithms use a pseudo-random generator, and so to some extent, you're at the mercy of the idiosyncrasies of that particular generator. I do agree with #AwokeKnowing that you can you also just do a random number between 1 and 4 and get the same result. I assume that the .Net randomization algorithm should suffice for most cases. For more info see:
http://en.wikipedia.org/wiki/Pseudorandom_number_generator
yes, that should work fine. just as >=75 would work too. if you just want 25%, you can go ahead and just do a random number between 1 and 4.
but please note, a 25% chance does NOT mean that out of 100 tries, he will win 25 times. It just means each time he has a 25% chance of winning. it's theoretically possible for him to win every single time. (but that will not happen, especially with a pseudo-random generator).
Internally the random number will be between 0 and 1 so it's just as random to use 4 as 1000, as far as that goes. add the parameter just projects it to the range you want.

How to use a Random number Generator in C#?

I created a Windows Forms application using Visual Studio Professional in C#. In my program I prompt the user to input the number of rolls he/she wants and then they press enter to get the numbers.
The numbers are shown in the same form under a label and get tallied up. I know how to tally the numbers know but I can't get the random number generator to generate the number of rolls the user inputs.
This is what i am doing:
Random randGen = new Random;
int oneRoll = randGen.Next(1,7) + randGen(1, 7);
I want the same program to occur the number of times the user wants. I tried a for loop but couldn't get what I wanted.
Make sure you create the Random Number generator just once.
Do NOT create it in each loop iteration.
Or, the numbers may not be random because the loop is so tight it will use the same time as the seed in the internal generator.
Try something like this:
Random randGen = new Random();
var rolls = new List<int>();
int sum = 0;
for (int i = 0; i < numberOfRolls; i++)
{
int randomNum1 = randGen.Next(1,7);
int randomNum2 = randGen.Next(1,7);
sum += randomNum1 + randomNum2;
rolls.Add(randomNum1);
rolls.Add(randomNum2);
}
Now all the separate rolls are in rolls, and the sum of them has already been calculated.
Edited to roll two dice, record them individually, and sum it all together.
int rolls = Console.ReadLine();
int total = 0;
Random randGen = new Random(System.DateTime.Now.Millisecond);
for(int i =0; i<rolls; i++)
{
int oneRoll = randGen.Next(1,7) + randGen.Next(1, 7);
Console.WriteLine("Rolled " + oneRoll);
total += oneRoll;
}
Console.WriteLine("Total " + total);
NB. you don't need the Millisecond bit, the seed just makes it more random
Your code is totally wrong...
Random randGen = new Random(DateTime.Now.Ticks); // unique seed, mostly
int result = 0;
for (int i = 0; i < number_of_rolls_the_user_wants; i++)
result += randGen.Next(2, 14); // (1 - 7) + (1 - 7) = 2 - 14 lol... >.>
Replace number_of_rolls_the_user_wants with the number of rolls the user wants.
result will hold the result.
Also please note that, if you generate many random numbers in a short time, use the same Random object!

Categories