|
That is not random numbers at all, that is an arbitrary permutation of a known set of numbers.
One way to achieve it is like this (in pseudo-code):
Collection coll=new Collection(holding all elements);
int n=coll.Count;
for(int i=n; i>0; i--) {
int j=RandomGenerator.Next(0, i);
int pick=coll[j];
coll.RemoveAt(j);
}
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
I would agree, but you'd have a RemoveAt which is not at the end but "anywhere" and that's slow. Why not just swap it with the last element?
|
|
|
|
|
Yes, swapping would work fine (you already had said that).
I set out to give a simple solution and no real code; there are many ways to do it, and for most of them several optimizations are possible.
Personally, for a small number of elements, I would do it quite differently: just generating the R-th permutation algorithmically, with a single random number R (in the range 0..n!-1) and a series of divisions. No collection, no objects, just divisions. But that is not the most obvious approach...
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
modified on Friday, May 6, 2011 10:12 AM
|
|
|
|
|
Ah factoradics, nice, I hadn't thought of that option for this case
|
|
|
|
|
You seem to have a univoter stuck to your backside.
|
|
|
|
|
Yea there's a whole page of univotes in my Rep History. Very odd.
Thanks for compensating
|
|
|
|
|
int maxSize = 10;
char[] chars = new char[62];
string a;
a = "1234567890";
chars = a.ToCharArray();
int size = maxSize;
byte[] data = new byte[1];
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
crypto.GetNonZeroBytes(data);
size = maxSize;
data = new byte[size];
crypto.GetNonZeroBytes(data);
StringBuilder resultUID = new StringBuilder(size);
foreach (byte b in data)
{
resultUID.Append(chars[b % (chars.Length - 1)]);
}
string generatedNumber = resultUID.ToString();
This will generate a number. It will never return the same number. You can specify the length of it by changing the maxSize. You can add letters by just updating string variable "a" if you want.
|
|
|
|
|
Random rnd = new Random(seed);
int num=rnd.Next(1,10);
Hope this can help you.
|
|
|
|
|
Hello,
How do I generate random numbers, say between 1 and 10, that return all the 10 numbers without repeatedly looping? Is there a way doing that in C#?
Thanks David, Luc Pattyn, PIEBALDconsult, orc_orc_orc, Prasanta_Prince for your all your responses and appreciate your time. I'll try the solutions provided by you
Little clarification on 'Repeatedly looping' (sorry for not being clear):
Lets say that if I want to generate random numbers between 1 and n, I use, say, rand() method that returns a random value every time I call this method. But there are chances that I get duplicate numbers being generated. So I need to skip (ignore) this duplicate number since it was already generated. But there is no guarantee that the same number doesn't appear again and again. So I need to keep looping until I get all the n numbers. The number of loops could grow as n grows, say 500. Is there a way to avoid the duplicates without doing a 'check' so that I can avoid extra loops? Performance is a concern.
Again thanks for your responses.
|
|
|
|
|
Hi meet_ssr,
You can construct a List<int> object with incrementing from 0 to n (say 0 to 10: 0,1,2,3,4,5,6,7,8,9); then pop at the index given by random(). Let me show you:
private static void NonRecurrentRandomize(int capacity)
{
List<int> orderedList = new List<int>(capacity);
for (int i = 0; i < capacity; i++)
{
orderedList.Add(i);
}
Random r = new Random();
while (orderedList.Count > 0)
{
int popIndex = r.Next(0, orderedList.Count);
Console.WriteLine(orderedList[popIndex]);
orderedList.RemoveAt(popIndex);
}
}
Hope this can be useful for you. (by the way i tested it in vs 2010)
Cheers.
Ozgur Sonmez.
|
|
|
|
|
Sonmez,
This is great. It is working fine to our needs.
Thanks for that.
|
|
|
|
|
meet_ssr;
You're welcome.
Glad having helped you.
do rather than say, be rather than do.
dr.ozgur.sonmez
|
|
|
|
|
I would create a hashset and add the numbers as they're generated. Since a hashset doesn't allow duplicate keys, you could just keep generating random numbers until you have 10 hashset entries.
HashSet<int> hash = new HashSet<int>();
Random random = new Random(DateTime.Now.Milliseconds);
int value = 0;
int final = 0;
do
{
try
{
if (hash.Count == 9)
{
final++;
hash.Add(final);
}
value = random.Next(1, 10);
hash.Add(value);
}
catch (Exception)
{
}
}
while (hash.Count < 10)
".45 ACP - because shooting twice is just silly" - JSOP, 2010 ----- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010 ----- "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
|
|
|
|
|
I coded a small contest . You can download it from here[^]
In my machine result is thus:
TestHashSet() completed in
00:00:00.0380860
TestList() completed in
00:00:00.0009766
do rather than say; be rather than do.
Ozgur Sonmez.
|
|
|
|
|
I haven't looked at your test, but if you'd like to time this code, have at it. I have no idea if it's any faster or slower, but it seems almost instantaneous to me Of course, every run is going to take a different amount of time because of the random.Next() function. The code below changes the range of random numbers if possible.
HashSet<int> hash = new HashSet<int>();
Random random = new Random(DateTime.Now.Millisecond);
int value = 0;
int start = 1;
int stop = 10;
do
{
try
{
value = random.Next(start, stop);
hash.Add(value);
if (value == start)
{
start++;
}
else if (value == stop)
{
stop--;
}
if (start == stop && hash.Count < 10)
{
hash.Add(start);
}
}
catch (Exception)
{
}
} while (hash.Count < 10);
".45 ACP - because shooting twice is just silly" - JSOP, 2010 ----- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010 ----- "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
|
|
|
|
|
meet_ssr wrote: Performance is a concern
cheers.
Ozgur Sonmez.
|
|
|
|
|
hi all.
now, i have datagridview in C#. i want add fix data into Datatable and show on datagridview. But, in line 2, i set value all column blank and not add button "show data" in this row. in datagridview it alway add button in row, but i want it not add button in line i will choice.
help me, please.
private static DataTable MakeTable()
{
// Create a new DataTable titled 'Names.'
DataTable namesTable = new DataTable("Names3");
//Add three column objects to the table.
DataColumn ClassificationNumber3 = new DataColumn();
ClassificationNumber3.DataType = System.Type.GetType("System.String");
ClassificationNumber3.ColumnName = "ClassificationNumber3";
namesTable.Columns.Add(ClassificationNumber3);
}
private static DataTable GetTable()
{
DataTable dt;
dt = MakeTable();
int i = 0;
DataRow dr;
try
{
for (i = 0; i < 20; i++)
{
dr = dt.NewRow();
// Then add the new row to the collection.
if (i <= 6)
{
dr["ClassificationNumber3"] = "03J";
//DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
//btn.HeaderText = "Click Data";
//btn.Text = "Click Here";
//btn.Name = "button3";
//btn.UseColumnTextForButtonValue = true;
//dataGridView3.Rows.Add(btn);
}
else if(i == 7)
{
dr["ClassificationNumber3"] = "";
}
else
{
dr["ClassificationNumber3"] = "03K";
}
dt.Rows.Add(dr);
}
thanks very much
nothing
|
|
|
|
|
Please re-format your question to reflect code in < pre > tags.
Clearly say what you are saying, so that we may be able to help you.
♫ 99 little bugs in the code,
99 bugs in the code
We fix a bug, compile it again
101 little bugs in the code ♫
|
|
|
|
|
|
I have a C# mobile application class. In that, there is a functionality which I use XmlTextWriter class. While compiling I am getting the following error:
The type 'System.Xml.XmlTextWriter' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
I have added reference of System.Xml through Add Reference and also use the namespace by the keyword 'using...'. Still I am getting the same error. Any Idea how to resolve this? I am using Visual Studio 2005 SP2. Is this belong to some setup issue? Please help.
Thanks
meeram395.
Success is the good fortune that comes from aspiration, desperation, perspiration and inspiration.
|
|
|
|
|
Click on System.Xml in the references section. Click properties, and see what the version number is. Make sure you are using the correct version.
|
|
|
|
|
The version and runtime version is 2.0.0.0 only. Is there any other settings need to change?
Success is the good fortune that comes from aspiration, desperation, perspiration and inspiration.
|
|
|
|
|
The only thing I've got to wonder is if this is the mobile version or the desktop version, and whether you have multiple projects in your solution (in which case you'd have the ensure the same was present in all projects this particular project was referenced in).
|
|
|
|
|
meeram395 wrote: I have a C# mobile application class.
Looks like it may not be available for mobile;
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2
I are Troll
|
|
|
|
|
Ok.
The error doesn't have any relation with mobile development. The error occurs in a simple class which is having XMLTextWriting functionality
Success is the good fortune that comes from aspiration, desperation, perspiration and inspiration.
|
|
|
|
|
meeram395 wrote: The error doesn't have any relation with mobile development.
It depends. Are you trying to use the class from the Compact Framework? Seems it is not part of that framework, and I doubt that you can simply reference libraries that where meant to run on a real desktop.
I are Troll
|
|
|
|