|
It depends on what you really want. For example 3 Years and 2 months could be between 1154 and 1158 days depending on which months you're actually talking about and if a leap year was included.
But I think for what you want you're going to have to just check the difference between the years/months/days yourself, I reckon something like this:
public struct Diff
{
public int Years;
public int Months;
public int Days;
};
public Diff Difference(DateTime start, DateTime end)
{
Diff diff = new Diff();
if (end.Day < start.Day)
{
end = end.AddMonths(-1);
int remainDays = DateTime.DaysInMonth(start.Year, start.Month) - start.Day;
diff.Days = remainDays + end.Day;
}
else
diff.Days = end.Day - start.Day;
if (end.Month < start.Month)
{
end = end.AddYears(-1);
diff.Months = 12 - (start.Month - end.Month);
}
else
diff.Months = end.Month - start.Month;
diff.Years = end.Year - start.Year;
return diff;
}
Which puts your example at 3 years and 3 months (and 13 days) since your further into September than you are into June, if you used 2008-06-12 ~ 2011-09-8 it would give 3 years 2 months 26 days. Which may or may not be quite what you want, but I think you get the idea.
Edit: Fixed function, mustn't write code when sleepy
|
|
|
|
|
Hello.
I am learning c# and reading my book "Head first c#"
In the interum, I would like to ask about generating random numbers.
My example uses the game "Roulette" where the wheel spins, and a number between 0 and 36 comes out.
I would like to ask the following questions:
1)What is the best (as in most random) way of generating a number between 0 and 36?
3)How would this be done if we had an animated roulette wheel, I ask this because if you play the game online, the ball may look as though it is ready to land on, say, 6, but then it appears to "bounce" to an adjacent number, is this down to a "random " value.
And lastly, lets say we are creating a random horse race, but the horse in question has a 80% chance of winning, how would we add this "odds" into a random value?
Thank you,
Stephen
|
|
|
|
|
Have a look at the Random[^] class.
|
|
|
|
|
stephen.darling wrote: )What is the best (as in most random) way of generating a number between 0 and
36?
With a roulette wheel.
As to the horse, he may be favored to win, but he doesn't have an "80% chance of winning". However, one of the techniques I like to use to select a random entity, from amomg various entities with varying chances of being selected, is to simulate putting slips into a hat, each entity may have a different number of slips in the hat, in proportion to their desired probability to be drawn.
|
|
|
|
|
PIEBALDconsult wrote: With a roulette wheel.
Are you suggesting there is no real way of randomising this?
PIEBALDconsult wrote: As to the horse, he may be favored to win, but he doesn't have an "80% chance of winning". However, one of the techniques I like to use to select a random entity, from amomg various entities with varying chances of being selected, is to simulate putting slips into a hat, each entity may have a different number of slips in the hat, in proportion to their desired probability to be drawn.
Please could you explain this a little further?
Thank you,
Steve
|
|
|
|
|
stephen.darling wrote: Please could you explain this a little further?
Given the concept of drawing a winner from a hat... in many situations, each entrant has one entry in the hat, and therefore an equal chance of being drawn (winning)... but, in some situations entrants have unequal probability of being drawn... this can be accomplished by the entrants having varying numbers of entries in the hat... when an entry is drawn, the more entries an entrant has, the greater the probability of being drawn. If you need to continue drawing other entrants, you can remove all the entries for the drawn entrant before continuing.
How this applies to horse racing, I don't know.
|
|
|
|
|
1) for random numbers
static Random _r = new Random();
static int F()
{
int n = _r.Next(0,36);
return n;
}
1a) - if you want to make bingo card
static void Main()
{
int[] numbers = new int[6];
for (int i = 0; i < numbers.Length; i++)
{
int a = F();
bool has = numbers.Contains(a);
if (has == true) {i--; }
else {
numbers[i]=a;
}
}
Array.Sort(numbers);
int j = 0;
foreach (int i in numbers)
{
Console.WriteLine("number at place " + (j+1).ToString() +" is " +i.ToString());
j++;
}
Console.ReadLine();
}
static Random _r = new Random();
static int F()
{
int n = _r.Next(0,36);
return n;
}
for horses and chances of winning
static void Main(string[] args)
{
int a = F();
if (a <= 80)
{
Console.Write("horse win!");
}
else { Console.Write("horse lose!"); }
Console.Write(" value of a is " + a.ToString());
Console.ReadLine();
}
static Random _r = new Random();
static int F()
{
int n = _r.Next(1, 100);
return n;
}
|
|
|
|
|
I'll take a bash at a slightly more realistic roulette simulator.
The roulette wheel works by having the ball travel a spiral path at a random velocity in one direction and the wheel spin at a different random velocity in the opposite direction. The number is determined by the degree of rotation of the wheel at the time the ball reaches a point in the spiral at which it touches the wheel.
Now, since i dont have the inclination to find the mathematical formula for a spiral we are going to assume that the ball is moving in decreasing circles.
we are also going to run the ball and wheel in seperate threads, but i'll leave you to sort out the threading
Ball thread:
public int RunAndReturnFinalAngle(int startRadius, int wheelRadius)
{
Random rng = new Random();
int sampleCount = 360;
int currentStep = 1;
int delayTime = rng.Next(10, 100);
int currentRadius = startRadius;
int radiusReduction = rng.Next(1, 5);
double ballX = 0;
double ballY = 0;
int angle = 0;
while (currentRadius > wheelRadius)
{
currentStep++;
if(currentStep > sampleCount){currentStep = 1;}
angle = 360 * (currentStep / sampleCount);
ballX = currentRadius * Math.Sin(angle);
ballY = currentRadius * Math.Cos(angle);
PositionBallGraphic(ballX, ballY);
currentRadius -= radiusReduction;
Thread.Sleep(delayTime);
}
return angle;
}
Now for the wheel, thats a lot simpler, simply run a loop modifying a value between 360 and 0 (remember its going the opposite direction) on a random delay (to set its speed) until the ball thread has done its thing.
At this point you will have the final angle of the ball and the final angle of the wheel.
public int GetNumberIndexForBall(int ballAngle, int wheelAngle)
{
int angleRelativeToWheel = ballAngle - wheelAngle;
return angleRelativeToWheel / 10;
}
Then you can use that index to get the wheel number from an ordered array/list of numbers on the wheel
Its very rough and hasnt been compiled/tested but that should provide a more real-to-life simulation of roulette than a simple random number between 1 and 36 and also give you graphical positioning data for the ball
modified on Thursday, September 1, 2011 4:12 PM
|
|
|
|
|
This sounds very interesting.
I will continue to learn what I am from the book, then I may be able to place this code into context.
Thank you, it seems much better than the standard Rand.next(0,35);
Regards,
Stephen
|
|
|
|
|
if you don't need the ball placement then i would recommend sticking with the simple random.next(), A true random number is not possible (at least generated electronically) but the random.next() is pretty good and any system deriving a random number from logic wrapped around a call to that method is at best going to be equally as good but, more likely, introduce bias (which the code i posted above most certainly does).
I posted that code more as a theoretical exercise in how one might simulate a (simplified) roulette wheel, for a system in which bias should be minimal (such as a gambling game in which real money is exchanging hands) it would be better to generate a random number through random.next() and then, having done this, calculate the animation of the ball (so that the ball itself is merely representing the already generated result and not playing a part in generating it)
Keep reading the book, but don't forget to get in there and get your hands dirty. Nothing teaches programming like attempting to program
|
|
|
|
|
Hi.
This is for fun, and not the real thing. It is going to be my first "real" project after the book. Although I would like it to be as "real" as possible.
I was actually thinking along the same lines.
1) Generate a random number 0-36
2) Animate the wheel, and somehow when the ball arrives near the generated number, make it "bounce a little" as though it was going to (random again) land on the number to the left or right before "faling" into place.
3) Use some kind of list/enum to look up the value and also get whether it is black or red (or green)
I have just started with the book now, and when I finish I am going to give this a real go.
Thank you for your advice and comments.
Kind Regards,
Stephen
|
|
|
|
|
Hi everyone,
Many off you know I ask a lot of questions, and although I am a complete beginner with c#, it is simply for the fact that I am impatient and want to get on with it, however, I now realise that I need to sit down with a good book.
Anyway, I have just purchased "Head First C#" 2nd edition.
I selected this book as some of the real-world projects appealed to me.
I would like to know if anyone has any experience with this book, and if I have made a good choice for a first book, and if I am likely to learn much in the way of windows development with c#?
Thank you,
p.s. LucPatton, if you are reading this, I am sure you will be happy (and relieved) that I finally got a book
|
|
|
|
|
Yes, it is really a very good book, especially for the beginners. Happy reading...
|
|
|
|
|
|
stephen.darling wrote: I now realise that I need to sit down with a good book.
Good decision
stephen.darling wrote: I have just purchased "Head First C#" 2nd edition.
That's being used in school 'ere; covers a lot, reads quite pleasantly.
stephen.darling wrote: if I have made a good choice for a first book
Yup, definitely worth the time
Bastard Programmer from Hell
|
|
|
|
|
Eddy Vluggen wrote: Good decision
Yes; I realise that now!
Eddy Vluggen wrote: That's being used in school 'ere; covers a lot, reads quite pleasantly.
Really? If it is being used in a school, must be OK then.
Eddy Vluggen wrote: Yup, definitely worth the time
Great. I will crack on and be back soon with my questions ha.
Thank you
|
|
|
|
|
Hi Stephen,
fyi, I found Jesse Liberty's books on C# from O'Reilly exceptionally good. And, currently I am studying Jon Skeet's 'C# in Depth," (Manning Press) which I regard as kind of the "Ph.D." level book on the subject (and one I suspect will take me years to really 'grok').
For Windows Forms, in addition to Liberty's book, I found Matthew MacDonald's books from APress excellent.
best, Bill
"In the River of Delights, Panic has not failed me." Jorge Luis Borges
|
|
|
|
|
Hello CP,
I'm currently messing around to build a plugin system and want to use subfolders.
After a bit of searching I found that adding a <probing privatepath=""/> element to app.config allowed subfolder usage.
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="lib" />
</assemblyBinding>
</runtime>
My only objection to this is that it is yet another file (one the user can edit :s) , my question is:
Can I merge this configuration file with the exe or is there another way to do this?
It would be preferable to put this in the manifest or something.
The first rule of CListCtrl is you do not talk about CListCtrl - kornman
modified on Sunday, August 28, 2011 11:13 AM
|
|
|
|
|
You can modify the configuration during runtime.
However whether it uses it to pick up assemblies is a different point.
Myself I don't see the utility. To create a plugin system you need to load from somewhere dynamically. That is the initial path. There isn't much point in having the framework (the loader) to provide options that require the plugin to follow a loading scheme that for most plugins shouldn't matter. So if the primary assembly is in director 'Bdir' then the plugin will probably have dependent assemblies in that directory and no other. And the standard assembly load mechanism will find those because the primary assembly was loaded from that.
But further note that the point of configuration is specifically so that users can modify it. And a plugin system is pretty much by it very nature suggesting that users are going to be responsible for it. So either the system is simple to begin with or one must assume that the users are intelligent enough to deal with it.
|
|
|
|
|
I am writing a C#.net windows desktop/windows form application in 2008 or 2010. When the application basically starts in program.cs in the main method., I am going to check to see if a user has access to this new desktop at all. I am also going to check to see what parts of the application the user has access to by looking at the active directory. When a user clicks on various tabs in the application there is going to be read only or read-write access. When there is read-write access, I going going to display the extra buttons only to those users only.
I have the following questions to ask:
1. Would you put this kind of logic in program.cs? If not, where would you suggest I put this logic and can you point me to a code reference I can use?
2. For the parts of the application where a user clicks on a tab that have either read-only or read-write access:
a. I was thinking of of storing the active directory groups that user has access to in global variables. However this is generally not a good idea due to not following good object oriented design princicples. if you were going to keep these values stored in variables, how would you accomplish this task?
2. Another option would be to do the same kind of basic ldap lookup everytime a user clicks on that tab on the desktop. How would you accomplish this option?
3. Do you have other options to suggest? if so, what are they? Can you explain your alternative option to me and/or point me to a url that will explain how you accomplish your optiuon?
|
|
|
|
|
dcof wrote: by looking at the active directory
What if there is no Active Directory?
dcof wrote: Would you put this kind of logic in program.cs?
No.
dcof wrote: where would you suggest
In a class that is designed for it.
dcof wrote: how would you accomplish this task
In a class that is designed for it.
dcof wrote: basic ldap lookup everytime a user clicks on that tab
Is that data likely to change?
dcof wrote: alternative option
Maybe investigate what's inside a Windows Principal[^]?
|
|
|
|
|
In reposne to your answers,I have the following additioanl questions:
1. Would you put this kind of logic in program.cs? No.
Why would you not put the code in this section? If the application is going to shutdown right away, why not close the app right away?
2. Would you have the program.cs call the code for LDAP right away?
|
|
|
|
|
Very very little goes into the main method; unless it's a simply command-line utility.
|
|
|
|
|
Your response, 'Very very little goes into the main method; unless it's a simply command-line utility.'.
Is this a requirement of microsoft? Is this a best practices standard?
If this is a requirement, are there any other parts of the application I should not put extra code into it?
|
|
|
|
|
dcof wrote: 1. Would you put this kind of logic in program.cs? If not, where would you suggest I put this logic and can you point me to a code reference I can use?
At some point you are going to have GUI components (classes) Which will NOT be part of program.cs (And with enough complexity the GUI components might be in their own assembly.
You are also going to need at least one class that does nothing but the Active Directory interaction. The GUI components call that class. That class then retrieves the necessary information.
The GUI components are then used in program.cs. In addition program.cs will use the above class to do the initial start up check. Presumably you are already planning on telling the users that they failed the initial Active Directory check.
dcof wrote: .<layer> Another option would be to do the same kind of basic ldap lookup everytime a user clicks on that tab on the desktop. How would you accomplish this option?
I would investigate the requirement that lead to this in the first place. Authentication and Authorization is best done with roles not users. A user belongs to a role. The role controls access. I would probably implement it in a database. I would probably cache it with a short expiration time.
|
|
|
|
|