代码如何产生不同长度的总是不同的字符串 [英] how the code produce always different string in different length

查看:124
本文介绍了代码如何产生不同长度的总是不同的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

您必须了解的是,Random并不是真正的随机.它实际上是一个伪随机数生成器-这意味着这些数字是根据统计算法生成的(在这种情况下,它是Donald Knuth算法的一种版本).如果每次都从相同的种子编号开始,那么每次都会生成相同的序列.在内部,Random类的种子基于系统时钟,但是如果将Random实例创建得足够近,则将拾取相同的值.

您在这里有两个实际选择:

1.使用相同的Random实例(不要每次都用这种方法重新创建它).
2.使用参数化的Random构造函数并传递滴答计数-两次调用之间已经经过了足够的滴答(除非您在无法保证它的多个线程中运行)以生成新种子.
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.


我认为这里需要两个随机数.
将此作为伪代码:

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.


这里有一些事情要做.
1)将randNum的定义移到类级别-每次需要随机数时都不要生成新实例.由于新实例是从时间开始部分初始化的,因此这将减少重复获得相同序列的机会.
2)不要使用NextDouble,然后将其乘以长度.而是使用随机整数: Random.Next [
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);
           }


它并没有花我太多的时间并产生重复的代码"



如何更正此问题,我想生成长度为5的唯一数字"

然后通过简单的方法进行操作:


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");
   }

这将返回其中包含随机数的5个字符串.

Which will return a 5 character string with a random number in it.


这篇关于代码如何产生不同长度的总是不同的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆