Click here to Skip to main content
15,901,205 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
C#
public static string createRandomString(int Length)
       {
           string _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
           Random randNum = new Random();
           int outputLength = (int)(randNum.NextDouble() * Length); //<<<<<<<<< moved out of loop
           char[] chars = new char[outputLength];  //<<<<<<<< use outputLength here
           // not used    int allowedCharCount = _allowedChars.Length;
           for (int i = 0; i < outputLength; i++)
           {
               chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())];
           }
           return new string(chars);
       }


hi this code some times generate same string and some times generate different string

how can i rectify this?i want to generate different string always please reply
Posted
Comments
[no name] 23-Jun-11 5:54am    
just a suggestion why dont u use GUID and trim top 6 or top 8 char.
Sergey Alexandrovich Kryukov 23-Jun-11 12:22pm    
Please do not re-post.
--SA

The thing you have to understand is that Random isn't truly random. It's actually a pseudo random number generator - which means that the numbers are generated based off a statistical algorithm (in this case, it's a version of Donald Knuth's algorithm). If you start from the same seed number every time, then you generate the same sequence every time. Internally, the seed for the Random class is based on the system clock, but if Random instances are created sufficiently close together the same value will be picked up.

You have two real choices here:

1. Use the same instance of Random (don't recreate it in this method every time).
2. Use the parameterised Random constructor and pass in the tick count - enough ticks will have elapsed between calls (unless you are running in multiple threads where it can't be guaranteed) to generate a new seed.
 
Share this answer
 
I think you need two randoms here.
Take this as pseudocode:

1. determine length of the string with a random (int stringlength). (you can use Next method with a Min and Max value, that avoids the casting to int)
2. initiate a stringbuilder (sb)
3. start a for loop : for(int i = 0; i < stringlength; i++)
4: in the for loop generate a NEW random number with the Next method with MIN value = 0 and MAX value = _allowedChars.Lenght-1; 
5. append the character with index number from step 4 to the stringbuilder (sb.Append(_allowedChars[randomintbetween0and_allowedcharslength]);)
6. when for loop finishes return sb.toString();


this should do the trick.
 
Share this answer
 
There are a few things to do here.
1) Move the definition of randNum to class level - do not generate a new instance each time you want a random number. Since the new instance is initialized partly from the time, this will reduce the chances of getting the same sequence repeated.
2) Don't use NextDouble, then multiply it by the length. Instead, use a random int instead: Random.Next[^]
private Random randNum = new Random();

public static string createRandomString(int Length)
   {
   string _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
   int outputLength = randNum.Next(Length);
   char[] chars = new char[outputLength];
   for (int i = 0; i < outputLength; i++)
      {
      chars[i] = _allowedChars[randNum.Next(allowedChars.Length)];
      }
   return new string(chars);
   }


"in this
private Random randNum = new Random();
 
        public static string createRandomNumbers()
           {
int Length=5;
  string _allowedChars = "0123456789";
           int outputLength = randNum.Next(Length); 
           char[] chars = new char[outputLength];  
           for (int i = 0; i < outputLength; i++)
              {
              chars[i] = _allowedChars[randNum.Next(allowedChars.Length)];
              }
           return new string(chars);
           }

it didnt take my length and produce duplicate code"



"how to rectify this i want to generate unique number in lenght = 5"

Then do it the easy way:
private static Random randNum = new Random();
public static string createRandomString()
   {
   return randNum.Next(100000).ToString("00000");
   }
Which will return a 5 character string with a random number in it.
 
Share this answer
 
v2
Comments
suryaswathi 23-Jun-11 6:48am    
in this

private Random randNum = new Random();

public static string createRandomNumbers()
{
int Length=5;
string _allowedChars = "0123456789";
int outputLength = randNum.Next(Length);
char[] chars = new char[outputLength];
for (int i = 0; i < outputLength; i++)
{
chars[i] = _allowedChars[randNum.Next(allowedChars.Length)];
}
return new string(chars);
}

it didnt take my length and produce duplicate code
suryaswathi 23-Jun-11 6:48am    
how to rectify this i want to generate unique number in lenght = 5
suryaswathi 23-Jun-11 7:21am    
private Random randNum = new Random();

public static string createRandomString(int Length)
{
string _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
int outputLength = randNum.Next(Length);
char[] chars = new char[outputLength];
for (int i = 0; i < outputLength; i++)
{
chars[i] = _allowedChars[randNum.Next(allowedChars.Length)];
}
return new string(chars);
}


some times this code generate any characters

i gave length 30 records to generate but i didnt give string in some records
why this pblm ? how to rectify? reply
suryaswathi 23-Jun-11 8:14am    
this code some time didnt generate any string..it must want to generate atleast two characters say the solution as soon as possible
OriginalGriff 23-Jun-11 8:20am    
Remember that random numbers are just that: random. They can produce low numbers as well as high ones...
If you need a minimum of two, then specify that in your outputLength assignment:
int outputLength = randNum.Next(2, Length);
What if outputLength == 0, as can arise ?

And you shouldn't you null-terminate the chars string ?
 
Share this answer
 
try this
System.Guid.NewGuid
this method is used to generate the unique identifiers.
 
Share this answer
 
"different string always"

Sorry but that cant be done. It's trivial math: |letter set| ^ numberOfLettersInString may be a quite large number, but it is definitely not infinite. Thus repetitions are bound to occurr if "always" is taken in the sense of "forever".

Cheers!

--MRB
 
Share this answer
 
Hi,

One simple solution.

1 ) Obtain clock tick (which is different at different times.)
2 ) and develop logic based on the clock tick counter.

This should work.

Regards,
Prafulla
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900