|
I have a simple method that takes a string as input and returns the time (in seconds) it takes to generate a another string that is the same – using System.Random.
private double timeOccurance2(string target)
{
string trial = string.Empty;
double intialTime = DateTime.Now.ToOADate();
Random rand = new Random();
while (trial != target)
{
StringBuilder b = new StringBuilder();
char[] ch = new char[target.Length];
for (int i = 0; i < target.Length; i++)
{
ch[i] = Convert.ToChar(Convert.ToInt32(Math.Floor(10 * rand.NextDouble() + 48)));
}
for (int i = 0; i < target.Length; i++)
{
b.Append(ch[i].ToString());
}
trial = b.ToString();
}
double finalTime = DateTime.Now.ToOADate();
return 24 * 60 * 60 * (finalTime - intialTime);
}
If I set target = “123246” and run the method repeatedly by clicking a button over and over, I get a random distribution of times, as expected.
Next, using the same target, I run multiple iterations of the method via BackGroundWorkers:
private void button1_Click(object sender, EventArgs e)
{
for (int i = 1; i <= 40; i++)
{
BackgroundWorker Computation = new BackgroundWorker();
Computation.DoWork += new DoWorkEventHandler(Computation_DoWork);
Computation.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Computation_RunWorkerCompleted);
Computation.RunWorkerAsync();
private void Computation_DoWork(object sender, DoWorkEventArgs e)
{
e.Result = timeOccurance2("123456").ToString();
}
private void Computation_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
richTextBox1.Text += (string)(e.Result);
richTextBox1.Text += (char)(10);
}
The result nearly always has a group of 4 numbers within the results that have nearly identical values. for example 407, 407, 422, 438. (Humm, my computer has 4 logical processors.) The cluster does not always appear at the beginning of the result set.
Why?
modified on Tuesday, February 2, 2010 9:38 AM
|
|
|
|
|
Probably because you are creating a new instance of Random, which takes the time as seed every time
|
|
|
|
|
See here.
"The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random.
To improve performance, create one Random to generate many random numbers over time, instead of repeatedly creating a new Random to generate one random number."
Me, I'm dishonest. And a dishonest man you can always trust to be dishonest. Honestly. It's the honest ones you want to watch out for...
|
|
|
|
|
|
Thanks,
I have the code block tag understood now. It really is more readable. Sorry.
I have tried instantiation of one Random instance as a class member in the button click event that starts the BackGroundWorkers. I place the instant creation just before the loop that creates the BGWs. When I use this approach the application either returns a set of results containing blocks of zeros mixed with blocks of identical times or it hangs.
Random rand;
private void button1_Click(object sender, EventArgs e)
{
rand=new Random();
for (int i = 1; i <= 40; i++)
{
BackgroundWorker Computation = new BackgroundWorker();
Computation.DoWork += new DoWorkEventHandler(Computation_DoWork);
Computation.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Computation_RunWorkerCompleted);
Computation.RunWorkerAsync();
}
}
private double timeOccurance2(string target)
{
string trial = string.Empty;
double intialTime = DateTime.Now.ToOADate();
int targetLength = target.Length;
while (trial != target)
{
StringBuilder b = new StringBuilder();
char[] ch = new char[target.Length];
for (int i = 0; i < target.Length; i++)
{
ch[i] = Convert.ToChar(Convert.ToInt32(Math.Floor(10 * rand.NextDouble() + 48)));
}
for (int i = 0; i < target.Length; i++)
{
b.Append(ch[i].ToString());
}
trial = b.ToString();
}
double finalTime = DateTime.Now.ToOADate();
return 24 * 60 * 60 * (finalTime - intialTime);
}
private void Computation_DoWork(object sender, DoWorkEventArgs e)
{
e.Result = timeOccurance2("124456").ToString();
}
private void Computation_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
richTextBox1.Text += (string)(e.Result);
richTextBox1.Text += (char)(10);
}
|
|
|
|
|
I did not read that. See my sig.
Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]
I only read code that is properly formatted, adding PRE tags is the easiest way to obtain that (one can edit an existing message!) [The QA section does it automatically now, I hope we soon get it on regular forums as well]
|
|
|
|
|
i have 2 user controls and a main form.
On form load, it will load usercontrol1. this is what i did.
public partial class main4 : Form<br />
{<br />
private UserControl1 userControl1 = new UserControl1();<br />
public main4()<br />
{<br />
InitializeComponent();<br />
this.Controls.Add(userControl1); <br />
} <br />
}
In userControl1, i've got a button that when clicked will navigate to userControl2.
My question is, how do i expose the button click event in userControl1 to the main form so that when the button is clicked, it will tell the main form to remove userControl1 and then add userControl2??
|
|
|
|
|
Well, your user control is private, so you'll have to implement a custom event that will reflect the button press back to the main form. Alternatively, just make the user control public, and then you can add an event to your mainform:
myMain4.userControl1.myButton.Click += ...
.45 ACP - because shooting twice is just silly ----- "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997 ----- "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001
|
|
|
|
|
Handle the Button's Click event in the user control and raise your own event:
public partial class UserControl1 : UserControl
{
public event EventHandler Button1Click;
public UserControl1()
{
InitializeComponent();
button1.Click += new EventHandler(button1_Click);
}
void button1_Click(object sender, EventArgs e)
{
OnButton1Click(e);
}
protected virtual void OnButton1Click(EventArgs e)
{
EventHandler eh = Button1Click;
if (eh != null)
eh(this, e);
}
}
Now the new Button1Click event is available for the Form/Container and can be handled like any other event.
|
|
|
|
|
hey both. tks i shall try and get back again
|
|
|
|
|
Hi i was wondering if there is an easy way to loop through a list to find the differences and at the "positive" differences to add that item to the list but at the "negative" differences to remove it from the list?
Doing a clear() and then add all the items isn't going to cut it because the list is databound to a DataGrid and it resets the selection
Thanks in advance and sorry my bad English gramma.
|
|
|
|
|
You could derive a new class like so:
public class MyListOfObjects : List<MyObject>{}
and then add a method like so:
public void AddUnique(MyObject obj)
which would see if the list contains obj , and if not, then add it.
At that point you can just loop through your new list and call the databound list's AddUnique method with each item in the new list.
.45 ACP - because shooting twice is just silly ----- "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997 ----- "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001
|
|
|
|
|
Thats just like doing a if(!list.contains(myobject)) { list.add(myobject); } just in a nice package and it also only solves the adding, not the removing which imo is the biggest problem because all the times the list have to be looped through starts to grow exponentially...
|
|
|
|
|
0) You gave us precious little info to work with here
1) You wanted a method to do it, I gave you one. Since I didn't know what you were working with (there was no real indication that you're working with intrinsic types), I couldn't recommend using a hash set. In fact, you talked about binding in a grid, so I presumed a complex object.
2) I suppose you could use Linq, but I'm not so sure that it would be any faster, and even if it was, I would still be prompted to do the list class override and pass the new list into it if for no other reason than to abstract the functionality out of the code that's using it, and into the code that should do it.
3) In the time we've been discussing it, you could have tried both ideas to see which one works best for you.
4) I wish the List object had a Merge method that allowed us to optionally omit non-unique objects.
.45 ACP - because shooting twice is just silly ----- "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997 ----- "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001
|
|
|
|
|
0 and 1) true, i'll try to explain a little better:
I have a base object that 4 other class inherit from, in the base object class there is a uinque guid(a ulong) that never will be different from object to object.
2) i've had a look at linq but i could only find a way to find equal objects
3) i already have a working solution but it's not fast enough, what it does is to put all the objects from the reading function into a new list, then a foreach that does a if(!oldList.contains(currentObject)) where i then add it, after that i do the same but with switched roles of the new and old list and add the guid of those to be removed to a new list because i can't modify a collection while enumerating and finally remove the objects from the oldList
and oh btw i the information my objects are read from another applications(well game) memory
Sorry if my previous post sounded rude because that wasn't my intention
|
|
|
|
|
Two options(for faster solutions):
1) you could use a dictionary<key, value> => extremely fast but you can only search(fast) based on the key. And some more memory required(for the keys)
2) Implement IComparable and use something like:
int idx = oldList.BinarySearch(currentObject);
if(idx<0)
|
|
|
|
|
actually i did use a dictionary but changed it to a list for various reasons, anyway i think i'll try to make a reverse for loop like this:
for(int i = GetLengthOfLongestList(); i>0; i--)
{
try
{
var currentNewObject=newList[i];
}
catch
{
}
and a
try
{
var currentOldObject=oldList[i];
}
catch
{
}
/after checks
oldList.removeAt(i);
oldList.add(currentNewObject);
}
}
modified on Wednesday, February 3, 2010 10:46 AM
|
|
|
|
|
Since .NET 3.5 we have a HashSet class that does that automatically. HashSet.Add[^]
Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]
I only read code that is properly formatted, adding PRE tags is the easiest way to obtain that. [The QA section does it automatically now, I hope we soon get it on regular forums as well]
|
|
|
|
|
But you can only compare intrinsic types. Is it really appropriate for complex objects where one or more properties could be required to be unique?
.45 ACP - because shooting twice is just silly ----- "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997 ----- "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001
|
|
|
|
|
hello again
1) how can i tell a connection that you should connect to Specified sql instance (sql server 2005) in the local machine ?
thanks!!!!
|
|
|
|
|
In the connection string, you need to provide instance name. i.e. localhost\SQLExpress (where SQLExpress is your instance name).
Server=myServerName\theInstanceName;
Also refer to this.[^]
|
|
|
|
|
Hello, I have a grid with a description column and 4 date columns. How do I modify the background color of the datepicker that is associated with the date columns? I set the Styles.Editor.BackColor property but that only changes the background color of the actual calender that drops down.
Thanks,
Lindsay
|
|
|
|
|
hi all
i have developed an windows application and want to build a (setup project) for it !
but there is some problem !
1) how can i find if there is another version of this application
2) warn user to repair or uninstall after installing new version! (like most of other software s)
3) find if there is any sqlserver2005 instances run on the services.msc if there is an instance but is not run!, then run it (without need the user to run this services manually)
please note me any thing in your mind about any of above sections!
thanks in advance
|
|
|
|
|
Hey my frnds .... I was working on a Dial-up networking for my customers ... which accepts connection from another PC by just dialing (only a modem and a phone line is needed in both PCs) which is not the concern of C# in my case .... But if I didnt not hide this connection from network connections in windows , another persons(may b professionals) can change things and might mess up my work .... So what i wanted here is that ... I want to write a C# code which will hide the connection i created and allows the user to run the connection @ any time with the help of C# code .... is that possible ... if yes please help me
Thank you
|
|
|
|
|
Sounds user hostile. A user has the right to be able to screw up his system any time he likes.
|
|
|
|
|
Thank you for your response
i know that my friend ... but my problem is not the users ... it is easy the users to tell that not to do any thing on it ... but if other professional come ...they may mess it up just to ruin my business ... any ways ... if it is not clear what i wanted is ... is it possible to write a code which will hide the connection from being viewed by the users and also to run it using C# code ??? .... if it is possible even other persons cant find it ..
|
|
|
|