Random String Generator在多个调用中创建相同的字符串

时间:2010-05-02 21:52:25

标签: asp.net vb.net string random

我已经构建了一个随机字符串生成器,但是我遇到了一个问题,即如果我在Page_Load方法中多次调用该函数,则该函数会返回相同的字符串两次。

这是代码

Public Class CustomStrings
    ''' <summary>'
    ''' Generates a Random String'
    ''' </summary>'
    ''' <param name="n">number of characters the method should generate</param>'
    ''' <param name="UseSpecial">should the method include special characters? IE: # ,$, !, etc.</param>'
    ''' <param name="SpecialOnly">should the method include only the special characters and excludes alpha numeric</param>'
    ''' <returns>a random string n characters long</returns>'
    Public Function GenerateRandom(ByVal n As Integer, Optional ByVal UseSpecial As Boolean = True, Optional ByVal SpecialOnly As Boolean = False) As String

        Dim chars As String() ' a character array to use when generating a random string'
        Dim ichars As Integer = 74 'number of characters to use out of the chars string'
        Dim schars As Integer = 0 ' number of characters to skip out of the characters string'

        chars = { _
         "A", "B", "C", "D", "E", "F", _
         "G", "H", "I", "J", "K", "L", _
         "M", "N", "O", "P", "Q", "R", _
         "S", "T", "U", "V", "W", "X", _
         "Y", "Z", "0", "1", "2", "3", _
         "4", "5", "6", "7", "8", "9", _
         "a", "b", "c", "d", "e", "f", _
         "g", "h", "i", "j", "k", "l", _
         "m", "n", "o", "p", "q", "r", _
         "s", "t", "u", "v", "w", "x", _
         "y", "z", "!", "@", "#", "$", _
         "%", "^", "&", "*", "(", ")", _
         "-", "+"}


        If Not UseSpecial Then ichars = 62 ' only use the alpha numeric characters out of "char"'
        If SpecialOnly Then schars = 62 : ichars = 74 ' skip the alpha numeric characters out of "char"'

        Dim rnd As New Random()
        Dim random As String = String.Empty
        Dim i As Integer = 0
        While i < n
            random += chars(rnd.[Next](schars, ichars))
            System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
        End While
        rnd = Nothing
        Return random
    End Function
End Class

但如果我打电话给这样的话

    Dim rnd1 As New CustomStrings
    Dim rnd2 As New CustomStrings

    Dim str1 As String = rnd1.GenerateRandom(5) 
    Dim str2 As String = rnd2.GenerateRandom(5) 

    rnd1 = Nothing
    rnd2 = Nothing

响应将是这样的

  
    

G * 3JQ
    G * 3JQ

  

我第二次打电话给它,它将是

  
    

3QM0 $
    3QM0 $

  

我错过了什么?我希望每个随机字符串都是唯一的。

5 个答案:

答案 0 :(得分:7)

这样做的原因是当你构造一个Random类的实例时,它会从时钟中播种出来,但是这个时钟的准确性不足以在每次调用时生成一个新的种子,如果你快速连续称呼它。

换句话说,这个:

Random r = new Random();
int i = r.Next(1000);
r = new Random();
int j = r.Next(1000);

很有可能在ij中生成相同的值。

您需要做的是:

  • 创建并缓存Random实例,以便它与每次调用使用的实例相同(但不幸的是,该类不是线程安全的,所以至少为每个线程保留一个缓存副本)
  • 使用每次调用更改的内容对其进行播种(这有点困难,因为使用序列值对其进行播种会产生可预测的随机数)

这是一个示例程序,它为每个线程创建一个单独的Random实例,并从全局随机对象中播种这些实例。同样,这可能会产生可预测的序列。

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace SO2755146
{
    public class Program
    {
        public static void Main()
        {
            List<Task> tasks = new List<Task>();
            for (int index = 0; index < 1000; index++)
                tasks.Add(Task.Factory.StartNew(() => Console.Out.WriteLine(RNG.Instance.Next(1000))));
            Task.WaitAll(tasks.ToArray());
        }
    }

    public static class RNG
    {
        private static Random _GlobalSeed = new Random();
        private static object _GlobalSeedLock = new object();

        [ThreadStatic]
        private static Random _Instance;

        public static Random Instance
        {
            get
            {
                if (_Instance == null)
                {
                    lock (_GlobalSeedLock)
                    {
                        _Instance = new Random(_GlobalSeed.Next());
                    }
                }
                return _Instance;
            }
        }
    }
}

如果您只想从时钟中播种每个随机实例,但至少每个线程生成随机序列,您可以像这样简化它:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace SO2755146
{
    public class Program
    {
        public static void Main()
        {
            List<Task> tasks = new List<Task>();
            for (int index = 0; index < 1000; index++)
                tasks.Add(Task.Factory.StartNew(() => Console.Out.WriteLine(RNG.Instance.Next(1000))));
            Task.WaitAll(tasks.ToArray());
        }
    }

    public static class RNG
    {
        [ThreadStatic]
        private static Random _Instance;

        public static Random Instance
        {
            get
            {
                if (_Instance == null)
                    _Instance = new Random();

                return _Instance;
            }
        }
    }
}

这可能会使两个线程彼此非常接近,以相同的值播种,因此需要权衡。

答案 1 :(得分:1)

独特的种子数方法

为了防止使用相同的种子值,为了停止生成相同的随机序列,您可以通过使用如下函数将GUID(隐式随机化)煮沸为int值来创建随机种子:

Private Function GetNewSeed() As Integer
    Dim arrBytes As Byte() = Guid.NewGuid().ToByteArray()  '16 bytes
    Dim seedNum As Integer = 0
    ' Boil GUID down 4 bytes at a time (size of int) and merge into Integer value
    For i As Integer = 0 To arrBytes.Length - 1 Step 4
        seedNum = seedNum Xor BitConverter.ToInt32(arrBytes, i)
    Next
    Return seedNum
End Function

使用返回的int为随机数生成器设定种子。

现在使用自定义函数GetNewSeed来解决问题。

Dim rnd1 As New Random( GetNewSeed )

这会处理问题的根源,即种子值。

答案 2 :(得分:1)

如果你想要没有序列的真正随机性,那么绝对不要使用System.Random函数。最好使用System.Security.Cryptography函数,理想情况下检查您的硬件是否支持.NET将自动使用的RNG(随机数生成)。

这是一个很好的例子: http://www.obviex.com/Samples/Password.aspx

答案 3 :(得分:1)

我使用以下方法创建一个独特的种子。

Session["seedRandom"] = 1;

在page_load创建了一个会话变量。 此会话变量将递增并添加到DateTime.Now.Ticks

private string getRandAlphaNum()
{
   int seed_value = (int)DateTime.Now.Ticks;
   seed_value = seed_value + Int32.Parse(Session["seedRandom"].ToString());
   //change the Session variable by incrementing its value to 1 after creating seed value.
   Session["seedRandom"] = Int32.Parse(Session["seedRandom"].ToString()) + 1;

   Random rand = new Random(seed_value);
   .....
   .....
}

因此每次我都会获得种子 DateTimeNow.Ticks +更新的会话变量

答案 4 :(得分:0)

我做了一些改动,对我来说似乎很好。我不喜欢使用关键字作为变量名。请注意,我移动了随机语句:

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim myCS As New CustomStrings
    Dim l As New List(Of String)

    For x As Integer = 1 To 10
        Dim s As String = myCS.GenerateRandom(5)
        l.Add(s)
    Next

    For x As Integer = 0 To l.Count - 1
        Debug.WriteLine(l(x))
    Next
    'Debug output
    'YGXiV
    'rfLmP
    'OVUW9
    '$uaMt
    '^RsPz
    'k&91k
    '(n2uN
    'ldbQQ
    'zYlP!
    '30kNt
End Sub

Public Class CustomStrings

    Private myRnd As New Random()
    Public Function GenerateRandom(ByVal n As Integer, _
                                   Optional ByVal UseSpecial As Boolean = True, _
                                   Optional ByVal SpecialOnly As Boolean = False) As String

        Dim ichars As Integer = 74 'number of characters to use out of the chars string'
        Dim schars As Integer = 0 ' number of characters to skip out of the characters string'

        Dim chars() As Char = New Char() {"A"c, "B"c, "C"c, "D"c, "E"c, "F"c, _
                                          "G"c, "H"c, "I"c, "J"c, "K"c, "L"c, _
                                          "M"c, "N"c, "O"c, "P"c, "Q"c, "R"c, _
                                          "S"c, "T"c, "U"c, "V"c, "W"c, "X"c, _
                                          "Y"c, "Z"c, "0"c, "1"c, "2"c, "3"c, _
                                          "4"c, "5"c, "6"c, "7"c, "8"c, "9"c, _
                                          "a"c, "b"c, "c"c, "d"c, "e"c, "f"c, _
                                          "g"c, "h"c, "i"c, "j"c, "k"c, "l"c, _
                                          "m"c, "n"c, "o"c, "p"c, "q"c, "r"c, _
                                          "s"c, "t"c, "u"c, "v"c, "w"c, "x"c, _
                                          "y"c, "z"c, "!"c, "@"c, "#"c, "$"c, _
                                          "%"c, "^"c, "&"c, "*"c, "("c, ")"c, _
                                          "-"c, "+"c}


        If Not UseSpecial Then ichars = 62 ' only use the alpha numeric characters out of "char"'
        If SpecialOnly Then schars = 62 : ichars = 74 ' skip the alpha numeric characters out of "char"'

        Dim rndStr As String = String.Empty
        Dim i As Integer = 0
        While i < n
            rndStr += chars(Me.myRnd.Next(schars, ichars))
            System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
        End While
        Return rndStr
    End Function
End Class

End Class