C# program using Random executes differently when running and interactively debugging [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm trying to make a Computer Vs. Computer guessing game. I've done it on python and matlab, but im having trouble doing it with c#.
I dont think that the application is executing the loop, but when using the debugger to step through the application it appears to work as intended.
using System;
using static System.Console;
namespace ComVsCom
{
class ComVsCom
{
static void Main(string[] args)
{
int rand, comp, pick = 0;
bool tri = false;
Random number = new Random();
rand = number.Next(1, 10);
Random computer = new Random();
comp = computer.Next(1, 10);
while (comp != rand && tri == false)
{
if (comp > rand)
WriteLine("Guess again you are too high!");
if (comp < rand)
WriteLine("Guess again you are too low!");
pick++;
WriteLine("{0} attempt", pick);
comp = computer.Next(1, 10);
if (comp == rand)
{
WriteLine("You got it! it took you {0} times the number was {1}", pick, rand);
tri = true;
}
}
}
}
}
Running the program normally, it terminates gives no output. However, when debugging the output given is what was expected and is something like:
Guess again you are too high!
3 attempt
Guess again you are too low
6 attempt
You got it! it took you 3 times the number was 6
Why does this work when using the debugger and not when running the program normally?

The problem is almost certainly that you are never entering the loop:
See https://msdn.microsoft.com/en-us/library/h343ddh9(v=vs.110).aspx
The default seed value is derived from the system clock and has finite resolution. As a result, different Random objects that are created in close succession by a call to the default constructor will have identical default seed values and, therefore, will produce identical sets of random numbers.
You create two Randoms at the start, then call exactly the same method on each of them. As expected based on the documentation, they produce exactly the same result. In the loop condition you check that these are different - they aren't, so the loop is never entered. Because all of your program logic is in that loop, none of it ever happens.
Note that your different behavior when debugging is probably due to stepping through the constructing of Randoms, making them occur at different times, so they will have different seed values and produce different sequences.

Related

Two instances running on separate threads crossed and duplicated data that it should not have [duplicate]

This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 3 years ago.
I've got an executable that runs my automated tests. Today I ran 4 sets of tests by running a .bat file that ran them all simultaneously.
The tests were building policies in our software. We got a SQL error that was caused by two instances entering the same policy holder information at the same time.
In each case the test randomly selects from a list of over 1500 names and addresses, so it's possible, though unlikely, that they both selected the same record.
What's baffling is that both also entered the same driver's license number, which is randomly generated in each case.
This has never happened before in 100's/1000's of runs.
Is it possible for two instances running the same executable file could somehow cross contaminate each other?
Random rnd = new Random();
else if (Crawlspace.DLState == "NEW MEXICO")
{
int DLNum = rnd.Next(100000000, 999999999);
Crawlspace.DLNumber = DLNum.ToString();
The tests were built this way to ensure a unique record in every case.
Thank you to Knoop. That explains what I wasn't understanding.
To fix, I will use this line to randomly generate the seed as well...
Random rand = new Random(Guid.NewGuid().GetHashCode());
(got this from a another very similar question)

C# variable used but never assigned

So I have been working on a program that calculates nearest and larger 3rd power to a number which is entered (if entered number is 20 then result is 27 because 3^3=27). However due to my lack of skills I have stumbled upon a problem. It seems that variable result is used but never assigned (even if its value is asigned to it in a for cycle) Here is the code:
namespace ConsoleApp6
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter a number: ");
int num = Convert.ToInt32(Console.ReadLine());
int result;
for(int i = num; (i * i * i) >= 0; i--)
{
result = i * i * i;
}
Console.WriteLine("Nest 3rd pow. is: " + result);
Console.WriteLine("Press any key to contiunue...");
Console.ReadLine();
}
}
}
Thank you for your answers.
The comments have probably dealt with your issue (you didn't set a value for result when you created it, the compiler can foresee a scenario where no loop runs and there is never any assignment, but you always use it. A "use of unassigned local variable" error arises), but I wanted to point out that your program is some way off solving the advertised problem of finding the next larger int cube than the entered number
To solve this, cube root the entered number, round it up to the next integer and cube it
Math.Pow(Math.Ceiling(Math.Pow(num, 1.0/3.0)), 3.0);
As things stand, I'm not really sure what you're aiming to achieve with the loop, and it looks like it will run however many times needed to set the result to 0 (it loops until i is zero, result is 0). Perhaps you intended to start i from 2 and increment i until result was larger than num, but that seems less efficient than doing the calc directly
One overall rule of good programming praxis is to initialize a variable on the declaration.
The compiler error says that you are using result when it has not been assigned. That's because in your for loop you can't predict that it will iterate at least one time (therefore there are scenarios where the variable is used without ever being assigned).
As have been mentioned before, this can be fixed by initializing the variable (0 is the standard)
int result = 0;

Why doesn't my code increase a variable everytime? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I am trying to make a code that loops through random numbers until it gets a six(this part is working) and then if you rolled a six in less than 6 tries but my code won't up my "amountOfMoney" variable if you get it in less than six. All it outputs is one even if you get under 6 two times in row. Here is the code:
class Program
{
static void Main(string[] args)
{
Start:
int attempt = 0;
int numberOfAttempts = 0;
int amountOfMoney = 0;
Random numberGen = new Random();
while (attempt != 6)
{
attempt = numberGen.Next(1, 7);
Console.WriteLine("Tom rolled: " + attempt + ".");
numberOfAttempts++;
}
Console.WriteLine("It took tom " + numberOfAttempts + " attempts to roll a six");
if(numberOfAttempts <= 6)
{
amountOfMoney++;
Console.WriteLine("You now have " + amountOfMoney + " dollars");
}
if(numberOfAttempts > 6)
{
amountOfMoney--;
Console.WriteLine("You now have " + amountOfMoney + " dollars");
}
Console.ReadKey();
goto Start;
}
}
You should be using the tools available to you to solve this (i.e the debugger), but it seems like you are new so I will risk the downvotes in an attempt to help you...
The code you have is pretty close to what you need. However the problem you have is a combination of using goto, and not understanding variable scope.
Let me be very clear: goto is very bad practice
When this line is hit:
goto Start;
It goes to the very top of your Main() method, the next 3 lines declare your variables and set them to 0. Thats why you are never able to persist the values.
You need to remove the goto and utilize a loop like you are already doing. Then put the variables you want to persist across loop iterations outside the scope of your new loop:
int amountOfMoney = 0;
while(someCondition)
{
//game logic here
amountOfMoney++;
}
//amountOfMoney has not reset every loop and now has all the changes you made to it
Console.WriteLine(amountOfMoney);
With your new loops you need to come up with an exit condition though. Is it a user's input that exits the loop (and the game), is it a fixed number of loops (use a for loop). That is up to you...
I made a simple "coin-flip" game here so you can see an example of what I am talking about. Doing the work for you wont help you learn but this should be more than enough to contextualize things for you.
I'm answering because this is actually an awesome teachable moment. What you have provided is one of the simplest examples of a very common design issue, an uncontextualized neologism. This label:
Start:
...seems innocent enough. But in the programming world, things are actually very, very, specific, and this label is nowhere near specific enough. What exactly is starting?
Whoever wrote this code...
int attempt = 0;
int numberOfAttempts = 0;
int amountOfMoney = 0;
...thought it was the start of the game.
Whoever wrote this code...
goto Start;
...thought it was the start of the round.
To fix this, make the label more specific, and put it in the right place.
P.S. Also, don't use goto and come up with an exit condition. But I think those lessons are less valuable.

How much does new Random() depends on time? [duplicate]

This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 5 years ago.
Yesterday I wrote my first answer at Programming Puzzles & Code Golf. The question said this:
Given an input string S, print S followed by a non-empty separator
in the following way:
Step 1: S has a 1/2 chance of being printed, and a 1/2 chance for the program to terminate.
Step 2: S has a 2/3 chance of being printed, and a 1/3 chance for the program to terminate.
Step 3: S has a 3/4 chance of being printed, and a 1/4 chance for the program to terminate.
…
Step n: S has a n/(n+1) chance of being printed, and a 1/(n+1) chance for the program to terminate.
So I went and wrote this code (ungolfed):
Action<string> g = s =>
{
var r = new Random();
for (var i = 2; r.Next(i++) > 0;)
Console.Write(s + " ");
};
This code works fine, but then someone said that I could save a few bytes creating the r variable inline, like this:
Action<string> g = s =>
{
for (var i = 2; new Random().Next(i++) > 0;)
Console.Write(s + " ");
};
I tried but when I executed the code, it always went in one of two possibilities:
Either the program halted before printing anything (the first call to Next() returns 0), or
The program never stops (the calls to Next() never return 0).
When I reverted the code to my original proposal, the program stopped more randomly as expected by the OP.
I know that the new Random() constructor depends on time, but how much? If I add a Sleep() call, the code behaviour starts to seem really random (but not much, the strings returned are still longer than the ones returned by the initial code):
Action<string> g = s =>
{
for (var i = 2; new Random().Next(i++) > 0; Thread.Sleep(1))
Console.Write(s + " ");
};
If I increment the sleep time to 10 ms, now the code really behaves like the original one.
So why is this? How much does the Random class depends on time? How exactly does the Random class seeds the number generator when calling the empty constructor?
Note: I know that creating a single Random object is the best practice, I just wanted to know a bit more than what the MSDN says:
The default seed value is derived from the system clock and has finite resolution.
What is that "finite resolution" the Random class default constructor uses as seed? How much time should we separate the construction of two Random objects to get different sequences? How much would those two different sequences differ when creating the Random instances too close in time?
What is that "finite resolution" the Random class default constructor uses as seed?
It uses Environment.TickCount which has a resolution of one millisecond.
How much time should we separate the construction of two Random objects to get different sequences?
As per the previous section, by at least one millisecond - or manually feed another seed to the constructor each time (or, well, reuse the same generator?)
How much would those two different sequences differ when creating the Random instances too close in time?
Matt Moss did a nice visualization in his Random Headaches from System.Random blog post:
Each row of the bitmap represents five first generated numbers with that seed (without preserving generated order):
As you can see, numbers are being selected from distinct but related sequences. As MSDN on Random says, "The chosen numbers... are sufficiently random for practical purposes."

The output is differ when debugging vs Step Into solution

I have a very strange problem that I never been in touch with in my entire life.
This is what I been up to:
I have programmed a game that involves you going to throw two dices and the sum of the two dices should be seven for you to win.
This is how the interface is built:
The textbox1 shows the value of first thrown dice.
The textbox2 shows the value of second thrown dice.
The textbox3 shows the sum of the both dices.
The button1 throws the dices.
This is the problem:
When i Debugg (F5) the application in Visual Studio 2013 Ultimate
the textboxes gets the exactly same value all the time. This is wrong, it shouldn't act like this.
When i Step Into (F11) the application/code the textboxes gets
different values, just as it should be, this is right, this is how the program should act.
Is there anyone that can help with this problem, i think that I have just missed a very small but a obvious thing that I have missed but I really can't find anything, I'm actually out of ideas!
Attachments
Here is all the files, I hope it will help you, the program is written in Swedish but I don't think that makes any problem, if it do, I can translate the whole solution to English.
The whole Solution: Throw_Dices.zip
The Code: Big picture on three screens of the code
From MSDN:
different Random objects that are created in close succession by a
call to the default constructor will have identical default seed
values and, therefore, will produce identical sets of random numbers
In your Kasta.cs, create a static instance of Random instead of multiple ones.
public class Tarning
{
private static Random ran = new Random();
int slump;
public int Kasta()
{
//Random ran = new Random();
slump = ran.Next(1, 6);
return slump;
}
}
Another possibility would be to create a seed manually. For instance like
public int Kasta()
{
byte[] seed = new byte[4];
new RNGCryptoServiceProvider().GetBytes(seed);
int seedInt = BitConverter.ToInt32(seed, 0);
Random ran = new Random(seedInt);
slump = ran.Next(1, 6);
return slump;
}
Instead of creating two Dice (Tarning ?)
Create one and roll it twice.
Or create both on start up, Or perhaps have a class that holds 2 dice.
and throw them again.
You should also google random and seeding, what's happening is from the same seed value, you get the same sequence of random numbers. Debugging is introducing enough of a delay between the new Random calls, that the seed (based on the clock) has changed between the two calls.
PS your button1Click handler
should set the three textbox values, not trigger textbox changed events which then set them. Imagine if you wanted to reuse your code, you'd have to create a UI to do it.
A better way would be to have a class that held two (or n) dice with a Roll method and a property that returned the result. Then you could reuse it without worrying about when and how.

Categories

Resources