<p>I need to generate a random integer between 1 and n (where n is a positive whole number) to use for a unit test. I don't need something overly complicated to ensure true randomness - just an old-fashioned random number.</p>

<p>How would I do that?</p>

[{'answer_id': 18680, 'author': 'Kibbee', 'author_id': 1862, 'author_profile': 'https://Stackoverflow.com/users/1862', 'pm_score': 7, 'selected': True, 'text': '<p>To get a random integer value between 1 and N (inclusive) you can use the following.</p>\n\n<pre><code>CInt(Math.Ceiling(Rnd() * n)) + 1\n</code></pre>\n'}, {'answer_id': 18684, 'author': 'Bill the Lizard', 'author_id': 1288, 'author_profile': 'https://Stackoverflow.com/users/1288', 'pm_score': 2, 'selected': False, 'text': "<pre><code>Public Function RandomNumber(ByVal n As Integer) As Integer\n    'initialize random number generator\n    Dim r As New Random(System.DateTime.Now.Millisecond)\n    Return r.Next(1, n)\nEnd Function\n</code></pre>\n"}, {'answer_id': 18687, 'author': 'Joseph Sturtevant', 'author_id': 317, 'author_profile': 'https://Stackoverflow.com/users/317', 'pm_score': 5, 'selected': False, 'text': '<p>Use <a href="http://msdn.microsoft.com/en-us/library/system.random.aspx" rel="noreferrer">System.Random</a>:</p>\n\n<pre><code>Dim MyMin As Integer = 1, MyMax As Integer = 5, My1stRandomNumber As Integer, My2ndRandomNumber As Integer\n\n\' Create a random number generator\nDim Generator As System.Random = New System.Random()\n\n\' Get a random number &gt;= MyMin and &lt;= MyMax\nMy1stRandomNumber = Generator.Next(MyMin, MyMax + 1) \' Note: Next function returns numbers _less than_ max, so pass in max + 1 to include max as a possible value\n\n\' Get another random number (don\'t create a new generator, use the same one)\nMy2ndRandomNumber = Generator.Next(MyMin, MyMax + 1)\n</code></pre>\n'}, {'answer_id': 2677819, 'author': 'Dan Tao', 'author_id': 105570, 'author_profile': 'https://Stackoverflow.com/users/105570', 'pm_score': 6, 'selected': False, 'text': "<p>As has been pointed out many times, the suggestion to write code like this is problematic:</p>\n\n<pre><code>Public Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer\n    Dim Generator As System.Random = New System.Random()\n    Return Generator.Next(Min, Max)\nEnd Function\n</code></pre>\n\n<p>The reason is that the constructor for the <code>Random</code> class provides a default seed based on the system's clock. On most systems, this has limited granularity -- somewhere in the vicinity of 20 ms. So if you write the following code, you're going to get the same number a bunch of times in a row:</p>\n\n<pre><code>Dim randoms(1000) As Integer\nFor i As Integer = 0 to randoms.Length - 1\n    randoms(i) = GetRandom(1, 100)\nNext\n</code></pre>\n\n<p>The following code addresses this issue:</p>\n\n<pre><code>Public Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer\n    ' by making Generator static, we preserve the same instance '\n    ' (i.e., do not create new instances with the same seed over and over) '\n    ' between calls '\n    Static Generator As System.Random = New System.Random()\n    Return Generator.Next(Min, Max)\nEnd Function\n</code></pre>\n\n<p>I threw together a simple program using both methods to generate 25 random integers between 1 and 100. Here's the output:</p>\n\n<pre><code>Non-static: 70 Static: 70\nNon-static: 70 Static: 46\nNon-static: 70 Static: 58\nNon-static: 70 Static: 19\nNon-static: 70 Static: 79\nNon-static: 70 Static: 24\nNon-static: 70 Static: 14\nNon-static: 70 Static: 46\nNon-static: 70 Static: 82\nNon-static: 70 Static: 31\nNon-static: 70 Static: 25\nNon-static: 70 Static: 8\nNon-static: 70 Static: 76\nNon-static: 70 Static: 74\nNon-static: 70 Static: 84\nNon-static: 70 Static: 39\nNon-static: 70 Static: 30\nNon-static: 70 Static: 55\nNon-static: 70 Static: 49\nNon-static: 70 Static: 21\nNon-static: 70 Static: 99\nNon-static: 70 Static: 15\nNon-static: 70 Static: 83\nNon-static: 70 Static: 26\nNon-static: 70 Static: 16\nNon-static: 70 Static: 75\n</code></pre>\n"}, {'answer_id': 13181177, 'author': 'Sergiu', 'author_id': 1791928, 'author_profile': 'https://Stackoverflow.com/users/1791928', 'pm_score': -1, 'selected': False, 'text': '<pre><code>Function xrand() As Long\n        Dim r1 As Long = Now.Day &amp; Now.Month &amp; Now.Year &amp; Now.Hour &amp; Now.Minute &amp; Now.Second &amp; Now.Millisecond\n        Dim RAND As Long = Math.Max(r1, r1 * 2)\n        Return RAND\nEnd Function\n</code></pre>\n\n<p>[BBOYSE]\nThis its the best way, from scratch :P</p>\n'}, {'answer_id': 19567863, 'author': 'Rogala', 'author_id': 2025711, 'author_profile': 'https://Stackoverflow.com/users/2025711', 'pm_score': 1, 'selected': False, 'text': "<p>If you are using Joseph's answer which is a great answer, and you run these back to back like this:</p>\n\n<pre><code>dim i = GetRandom(1, 1715)\ndim o = GetRandom(1, 1715)\n</code></pre>\n\n<p>Then the result could come back the same over and over because it processes the call so quickly.  This may not have been an issue in '08, but since the processors are much faster today, the function doesn't allow the system clock enough time to change prior to making the second call.  </p>\n\n<p>Since the System.Random() function is based on the system clock, we need to allow enough time for it to change prior to the next call.  One way of accomplishing this is to pause the current thread for 1 millisecond.  See example below:</p>\n\n<pre><code>Public Function GetRandom(ByVal min as Integer, ByVal max as Integer) as Integer\n    Static staticRandomGenerator As New System.Random\n    max += 1\n    Return staticRandomGenerator.Next(If(min &gt; max, max, min), If(min &gt; max, min, max))\nEnd Function\n</code></pre>\n"}, {'answer_id': 21461274, 'author': 'Shawn Kovac', 'author_id': 2840284, 'author_profile': 'https://Stackoverflow.com/users/2840284', 'pm_score': 2, 'selected': False, 'text': '<p>All the answers so far have problems or bugs (plural, not just one). I will explain. But first I want to compliment Dan Tao\'s insight to use a static variable to remember the Generator variable so calling it multiple times will not repeat the same # over and over, plus he gave a very nice explanation. But his code suffered the same flaw that most others have, as i explain now.</p>\n\n<p>MS made their Next() method rather odd. the Min parameter is the inclusive minimum as one would expect, but the Max parameter is the <em>exclusive</em> maximum as one would NOT expect. in other words, if you pass min=1 and max=5 then your random numbers would be any of 1, 2, 3, or 4, but it would never include 5. This is the first of two potential bugs in all code that uses Microsoft\'s Random.Next() method.</p>\n\n<p>For a <em>simple</em> answer (but still with other possible but rare problems) then you\'d need to use:</p>\n\n<pre><code>Private Function GenRandomInt(min As Int32, max As Int32) As Int32\n    Static staticRandomGenerator As New System.Random\n    Return staticRandomGenerator.Next(min, max + 1)\nEnd Function\n</code></pre>\n\n<p>(I like to use <code>Int32</code> rather than <code>Integer</code> because it makes it more clear how big the int is, plus it is shorter to type, but suit yourself.)</p>\n\n<p>I see two potential problems with this method, but it will be suitable (and correct) for most uses. So if you want a <em>simple</em> solution, i believe this is correct.</p>\n\n<p>The only 2 problems i see with this function is:\n1: when Max = Int32.MaxValue so adding 1 creates a numeric overflow. altho, this would be rare, it is still a possibility.\n2: when min > max + 1. when min = 10 and max = 5 then the Next function throws an error. this may be what you want. but it may not be either. or consider when min = 5 and max = 4. by adding 1, 5 is passed to the Next method, but it does not throw an error, when it really is an error, but Microsoft .NET code that i tested returns 5. so it really is not an \'exclusive\' max when the max = the min. but when max &lt; min for the Random.Next() function, then it throws an ArgumentOutOfRangeException. so Microsoft\'s implementation is really inconsistent and buggy too in this regard.</p>\n\n<p>you may want to simply swap the numbers when min > max so no error is thrown, but it totally depends on what is desired. if you want an error on invalid values, then it is probably better to also throw the error when Microsoft\'s exclusive maximum (max + 1) in our code equals minimum, where MS fails to error in this case.</p>\n\n<p>handling a work-around for when max = Int32.MaxValue is a little inconvenient, but i expect to post a thorough function which handles both these situations. and if you want different behavior than how i coded it, suit yourself. but be aware of these 2 issues.</p>\n\n<p>Happy coding!</p>\n\n<p>Edit:\nSo i needed a random integer generator, and i decided to code it \'right\'. So if anyone wants the full functionality, here\'s one that actually works. (But it doesn\'t win the simplest prize with only 2 lines of code. But it\'s not really complex either.)</p>\n\n<pre><code>\'\'\' &lt;summary&gt;\n\'\'\' Generates a random Integer with any (inclusive) minimum or (inclusive) maximum values, with full range of Int32 values.\n\'\'\' &lt;/summary&gt;\n\'\'\' &lt;param name="inMin"&gt;Inclusive Minimum value. Lowest possible return value.&lt;/param&gt;\n\'\'\' &lt;param name="inMax"&gt;Inclusive Maximum value. Highest possible return value.&lt;/param&gt;\n\'\'\' &lt;returns&gt;&lt;/returns&gt;\n\'\'\' &lt;remarks&gt;&lt;/remarks&gt;\nPrivate Function GenRandomInt(inMin As Int32, inMax As Int32) As Int32\n    Static staticRandomGenerator As New System.Random\n    If inMin &gt; inMax Then Dim t = inMin : inMin = inMax : inMax = t\n    If inMax &lt; Int32.MaxValue Then Return staticRandomGenerator.Next(inMin, inMax + 1)\n    \' now max = Int32.MaxValue, so we need to work around Microsoft\'s quirk of an exclusive max parameter.\n    If inMin &gt; Int32.MinValue Then Return staticRandomGenerator.Next(inMin - 1, inMax) + 1 \' okay, this was the easy one.\n    \' now min and max give full range of integer, but Random.Next() does not give us an option for the full range of integer.\n    \' so we need to use Random.NextBytes() to give us 4 random bytes, then convert that to our random int.\n    Dim bytes(3) As Byte \' 4 bytes, 0 to 3\n    staticRandomGenerator.NextBytes(bytes) \' 4 random bytes\n    Return BitConverter.ToInt32(bytes, 0) \' return bytes converted to a random Int32\nEnd Function\n</code></pre>\n'}, {'answer_id': 27227997, 'author': 'Binny', 'author_id': 1821206, 'author_profile': 'https://Stackoverflow.com/users/1821206', 'pm_score': 0, 'selected': False, 'text': '<pre><code>Dim rnd As Random = New Random\nrnd.Next(n)\n</code></pre>\n'}, {'answer_id': 32043953, 'author': 'achar', 'author_id': 3915785, 'author_profile': 'https://Stackoverflow.com/users/3915785', 'pm_score': 2, 'selected': False, 'text': "<p>You should create a pseudo-random number generator only once:</p>\n\n<pre><code>Dim Generator As System.Random = New System.Random()\n</code></pre>\n\n<p>Then, if an integer suffices for your needs, you can use:</p>\n\n<pre><code>Public Function GetRandom(myGenerator As System.Random, ByVal Min As Integer, ByVal Max As Integer) As Integer\n'min is inclusive, max is exclusive (dah!)\nReturn myGenerator.Next(Min, Max + 1)\nEnd Function\n</code></pre>\n\n<p>as many times as you like. Using the wrapper function is justified only because the maximum value is exclusive - I know that the random numbers work this way but the definition of .Next is confusing.</p>\n\n<p>Creating a generator every time you need a number is in my opinion wrong; the pseudo-random numbers do not work this way.</p>\n\n<p>First, you get the problem with initialization which has been discussed in the other replies. If you initialize once, you do not have this problem.</p>\n\n<p>Second, I am not at all certain that you get a valid sequence of random numbers; rather, you get a collection of the first number of multiple different sequences which are seeded automatically based on computer time. I am not certain that these numbers will pass the tests that confirm the randomness of the sequence.</p>\n"}, {'answer_id': 35563352, 'author': 'Wais', 'author_id': 2514566, 'author_profile': 'https://Stackoverflow.com/users/2514566', 'pm_score': 3, 'selected': False, 'text': '<p>Microsoft Example <a href="https://msdn.microsoft.com/en-us/library/f7s023d2%28v=vs.90%29.aspx" rel="noreferrer">Rnd Function</a></p>\n\n<p><a href="https://msdn.microsoft.com/en-us/library/f7s023d2%28v=vs.90%29.aspx" rel="noreferrer">https://msdn.microsoft.com/en-us/library/f7s023d2%28v=vs.90%29.aspx</a></p>\n\n<p>1- Initialize the random-number generator.</p>\n\n<pre><code>Randomize()\n</code></pre>\n\n<p>2 - Generate random value between 1 and 6. </p>\n\n<pre><code>Dim value As Integer = CInt(Int((6 * Rnd()) + 1))\n</code></pre>\n'}, {'answer_id': 39948531, 'author': 'Zibri', 'author_id': 236062, 'author_profile': 'https://Stackoverflow.com/users/236062', 'pm_score': 0, 'selected': False, 'text': '<p>Just for reference, VB NET Fuction definition for RND and RANDOMIZE (which should give the same results of BASIC (1980 years) and all versions after is:</p>\n\n<pre><code>Public NotInheritable Class VBMath\n    \' Methods\n    Private Shared Function GetTimer() As Single\n        Dim now As DateTime = DateTime.Now\n        Return CSng((((((60 * now.Hour) + now.Minute) * 60) + now.Second) + (CDbl(now.Millisecond) / 1000)))\n    End Function\n\n    Public Shared Sub Randomize()\n        Dim timer As Single = VBMath.GetTimer\n        Dim projectData As ProjectData = ProjectData.GetProjectData\n        Dim rndSeed As Integer = projectData.m_rndSeed\n        Dim num3 As Integer = BitConverter.ToInt32(BitConverter.GetBytes(timer), 0)\n        num3 = (((num3 And &amp;HFFFF) Xor (num3 &gt;&gt; &amp;H10)) &lt;&lt; 8)\n        rndSeed = ((rndSeed And -16776961) Or num3)\n        projectData.m_rndSeed = rndSeed\n    End Sub\n\n    Public Shared Sub Randomize(ByVal Number As Double)\n        Dim num2 As Integer\n        Dim projectData As ProjectData = ProjectData.GetProjectData\n        Dim rndSeed As Integer = projectData.m_rndSeed\n        If BitConverter.IsLittleEndian Then\n            num2 = BitConverter.ToInt32(BitConverter.GetBytes(Number), 4)\n        Else\n            num2 = BitConverter.ToInt32(BitConverter.GetBytes(Number), 0)\n        End If\n        num2 = (((num2 And &amp;HFFFF) Xor (num2 &gt;&gt; &amp;H10)) &lt;&lt; 8)\n        rndSeed = ((rndSeed And -16776961) Or num2)\n        projectData.m_rndSeed = rndSeed\n    End Sub\n\n    Public Shared Function Rnd() As Single\n        Return VBMath.Rnd(1!)\n    End Function\n\n    Public Shared Function Rnd(ByVal Number As Single) As Single\n        Dim projectData As ProjectData = ProjectData.GetProjectData\n        Dim rndSeed As Integer = projectData.m_rndSeed\n        If (Number &lt;&gt; 0) Then\n            If (Number &lt; 0) Then\n                Dim num1 As UInt64 = (BitConverter.ToInt32(BitConverter.GetBytes(Number), 0) And &amp;HFFFFFFFF)\n                rndSeed = CInt(((num1 + (num1 &gt;&gt; &amp;H18)) And CULng(&amp;HFFFFFF)))\n            End If\n            rndSeed = CInt((((rndSeed * &amp;H43FD43FD) + &amp;HC39EC3) And &amp;HFFFFFF))\n        End If\n        projectData.m_rndSeed = rndSeed\n        Return (CSng(rndSeed) / 1.677722E+07!)\n    End Function\n\nEnd Class\n</code></pre>\n\n<p>While the Random CLASS is:</p>\n\n<pre><code>Public Class Random\n    \' Methods\n    &lt;__DynamicallyInvokable&gt; _\n    Public Sub New()\n        Me.New(Environment.TickCount)\n    End Sub\n\n    &lt;__DynamicallyInvokable&gt; _\n    Public Sub New(ByVal Seed As Integer)\n        Me.SeedArray = New Integer(&amp;H38  - 1) {}\n        Dim num4 As Integer = If((Seed = -2147483648), &amp;H7FFFFFFF, Math.Abs(Seed))\n        Dim num2 As Integer = (&amp;H9A4EC86 - num4)\n        Me.SeedArray(&amp;H37) = num2\n        Dim num3 As Integer = 1\n        Dim i As Integer\n        For i = 1 To &amp;H37 - 1\n            Dim index As Integer = ((&amp;H15 * i) Mod &amp;H37)\n            Me.SeedArray(index) = num3\n            num3 = (num2 - num3)\n            If (num3 &lt; 0) Then\n                num3 = (num3 + &amp;H7FFFFFFF)\n            End If\n            num2 = Me.SeedArray(index)\n        Next i\n        Dim j As Integer\n        For j = 1 To 5 - 1\n            Dim k As Integer\n            For k = 1 To &amp;H38 - 1\n                Me.SeedArray(k) = (Me.SeedArray(k) - Me.SeedArray((1 + ((k + 30) Mod &amp;H37))))\n                If (Me.SeedArray(k) &lt; 0) Then\n                    Me.SeedArray(k) = (Me.SeedArray(k) + &amp;H7FFFFFFF)\n                End If\n            Next k\n        Next j\n        Me.inext = 0\n        Me.inextp = &amp;H15\n        Seed = 1\n    End Sub\n\n    Private Function GetSampleForLargeRange() As Double\n        Dim num As Integer = Me.InternalSample\n        If ((Me.InternalSample Mod 2) = 0) Then\n            num = -num\n        End If\n        Dim num2 As Double = num\n        num2 = (num2 + 2147483646)\n        Return (num2 / 4294967293)\n    End Function\n\n    Private Function InternalSample() As Integer\n        Dim inext As Integer = Me.inext\n        Dim inextp As Integer = Me.inextp\n        If (++inext &gt;= &amp;H38) Then\n            inext = 1\n        End If\n        If (++inextp &gt;= &amp;H38) Then\n            inextp = 1\n        End If\n        Dim num As Integer = (Me.SeedArray(inext) - Me.SeedArray(inextp))\n        If (num = &amp;H7FFFFFFF) Then\n            num -= 1\n        End If\n        If (num &lt; 0) Then\n            num = (num + &amp;H7FFFFFFF)\n        End If\n        Me.SeedArray(inext) = num\n        Me.inext = inext\n        Me.inextp = inextp\n        Return num\n    End Function\n\n    &lt;__DynamicallyInvokable&gt; _\n    Public Overridable Function [Next]() As Integer\n        Return Me.InternalSample\n    End Function\n\n    &lt;__DynamicallyInvokable&gt; _\n    Public Overridable Function [Next](ByVal maxValue As Integer) As Integer\n        If (maxValue &lt; 0) Then\n            Dim values As Object() = New Object() { "maxValue" }\n            Throw New ArgumentOutOfRangeException("maxValue", Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", values))\n        End If\n        Return CInt((Me.Sample * maxValue))\n    End Function\n\n    &lt;__DynamicallyInvokable&gt; _\n    Public Overridable Function [Next](ByVal minValue As Integer, ByVal maxValue As Integer) As Integer\n        If (minValue &gt; maxValue) Then\n            Dim values As Object() = New Object() { "minValue", "maxValue" }\n            Throw New ArgumentOutOfRangeException("minValue", Environment.GetResourceString("Argument_MinMaxValue", values))\n        End If\n        Dim num As Long = (maxValue - minValue)\n        If (num &lt;= &amp;H7FFFFFFF) Then\n            Return (CInt((Me.Sample * num)) + minValue)\n        End If\n        Return (CInt(CLng((Me.GetSampleForLargeRange * num))) + minValue)\n    End Function\n\n    &lt;__DynamicallyInvokable&gt; _\n    Public Overridable Sub NextBytes(ByVal buffer As Byte())\n        If (buffer Is Nothing) Then\n            Throw New ArgumentNullException("buffer")\n        End If\n        Dim i As Integer\n        For i = 0 To buffer.Length - 1\n            buffer(i) = CByte((Me.InternalSample Mod &amp;H100))\n        Next i\n    End Sub\n\n    &lt;__DynamicallyInvokable&gt; _\n    Public Overridable Function NextDouble() As Double\n        Return Me.Sample\n    End Function\n\n    &lt;__DynamicallyInvokable&gt; _\n    Protected Overridable Function Sample() As Double\n        Return (Me.InternalSample * 4.6566128752457969E-10)\n    End Function\n\n\n    \' Fields\n    Private inext As Integer\n    Private inextp As Integer\n    Private Const MBIG As Integer = &amp;H7FFFFFFF\n    Private Const MSEED As Integer = &amp;H9A4EC86\n    Private Const MZ As Integer = 0\n    Private SeedArray As Integer()\nEnd Class\n</code></pre>\n'}, {'answer_id': 67386995, 'author': 'Bart Hofland', 'author_id': 4174789, 'author_profile': 'https://Stackoverflow.com/users/4174789', 'pm_score': 0, 'selected': False, 'text': '<p>I see a lot of answers of users that are not satisfied with using <code>System.Random</code>.</p>\n<p>Despite the fact that I personally would still use <code>System.Random</code>, I was thinking about a way to use a GUID as the base for a random value. A GUID can be converted to a byte array using its <code>ToByteArray</code> method, and the resulting byte array can be converted to a numeric value using a <code>BitConverter</code>.</p>\n<pre class="lang-vb prettyprint-override"><code>\'Function for reuse (min is inclusive and max is exclusive)\nFunction GetRandom(min As Integer, max As Integer) As Integer\n    Return BitConverter.ToUInt64(Guid.NewGuid.ToByteArray) Mod (max - min) + min\nEnd Function\n</code></pre>\n<pre class="lang-vb prettyprint-override"><code>\'one-liner specific for your purpose (n is exclusive)\nBitConverter.ToUInt64(Guid.NewGuid.ToByteArray) Mod (n - 1) + 1\n</code></pre>\n<p>Note that this is just a little thought experiment. I haven\'t tested the performance, nor have I investigated the actual &quot;randomness&quot; of the results. But for your purpose, it might just do the job.</p>\n<p>The accepted answer uses the <a href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualbasic.vbmath.rnd" rel="nofollow noreferrer"><code>Microsoft.VisualBasic.VBMath.Rnd</code></a> method, which indeed offers a simple and attractive oneliner, but I personally would avoid writing new code that uses the <code>Microsoft.VisualBasic</code> namespace.</p>\n'}]
['https://Stackoverflow.com/questions/18676', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/225/']