Generate a sequence of 5 random numbers - vb.net

this code generates a single number, how could I generate more?
Dim randomNumber As Integer = rnd.Next(0, 81)
I would like to generate more random numbers using this code, but how could I do that?

As you generate your 5 random numbers, you need a place to store each number. I chose a List(Of T) because I don't have to know how many items I want to add in advance. You could also use an array.
When you instantiate the Random class without a seed then the class uses the system clock as the seed. This is the usual way to do it.
Private Sub OPCode(URL As String)
Dim Rnd As New Random() 'No seed!
Dim lst As New List(Of Integer)
For i = 0 To 4
lst.Add(Rnd.Next(0, 81))
Next
For Each i In lst
TextBox1.Text &= i.ToString & vbCrLf
Next
End Sub

Related

newline on a label vb.net within a for next loop

how would i get a newline between each random 8 digit ID that I created, on the one label?
Public Class Form1
'Write a program to display 1000 8-character random user IDs in a text
'box after you click a button. Make sure the program verifies that none Of the IDs are identical.
'Each userid should include a mixture Of alphabetic characters And numbers.
Private Sub btnGenerateRandomID_Click(sender As Object, e As EventArgs) Handles btnGenerateRandomID.Click
Dim strChar As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Dim rand As New Random
Dim strID As String
Dim IdCheck As New List(Of String) With {.Capacity = 1000}
For count_ids As Integer = 0 To 999
For count_chars As Integer = 0 To 7
strID += strChar(rand.Next(0, 62))
Next
If Not IdCheck.Contains(strID) Then
IdCheck.Add(strID)
End If
Next
lblRandomId.Text = strID
Couple of things...
You need to reset strID between each generated ID, otherwise it will just become longer, and longer, and longer, and...you get the idea.
Instead of hard-coding a random number between 0 and 62, use the .Length property of strChar. This way if you change the characters available in that string, your code will not need to be changed with respect to the random character being picked.
Speaking of Random, you should declare that as static so that it only gets instantiated once and gets re-used with each call. Otherwise, if you click really fast you can actually end up with the same results since creating an instance of Random with no parameter uses the system clock as the seed.
If your ID was not unique, then it won't be added. In that case, you'd end up with fewer than 1000 IDs. You have to keep looping around until you find one that isn't in the list.
Lastly, I'd just use String.Join() with Environment.NewLine to add all of the IDs to the Label.
Here's what those changes might look like:
Dim strChar As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Static rand As New Random
Dim strID As String
Dim IdCheck As New List(Of String) With {.Capacity = 1000} 'copyright stackoverflow inquiry
For count_ids As Integer = 0 To 999
Do
strID = ""
For count_chars As Integer = 0 To 7
strID += strChar(rand.Next(strChar.Length))
Next
Loop While IdCheck.Contains(strID)
IdCheck.Add(strID)
Next
lblRandomId.Text = String.Join(Environment.NewLine, IdCheck)

Random() doesn't seem to be so random at all

Random() doesn't seem to be so random at all, it keeps repeating the pattern all the time.
How can I make this "more" random?
Dim ioFile As New System.IO.StreamReader("C:\names.txt")
Dim lines As New List(Of String)
Dim rnd As New Random()
Dim line As Integer
While ioFile.Peek <> -1
lines.Add(ioFile.ReadLine())
End While
line = rnd.Next(lines.Count + 0)
NAMES.AppendText(lines(line).Trim())
ioFile.Close()
ioFile.Dispose()
Clipboard.SetText(NAMES.Text)
This works fine for me. I changed a few things like implementing a using block, removed a redundant addition of 0, and added a loop to test 100 times out to debug. a sample of 200 that you are just "eyeballing" is not enough to say that a random sequence is "not working".
Using ioFile As New System.IO.StreamReader("C:\names.txt")
Dim lines As New List(Of String)
Dim rnd As New Random()
Dim line As Integer
While ioFile.Peek <> -1
lines.Add(ioFile.ReadLine())
End While
For i As Integer = 1 To 100
line = rnd.Next(lines.Count)
Debug.WriteLine(lines(line).Trim())
Next
End Using
You don't need a stream reader to read a text file. File.ReadAllLines will return an array of lines in the file. Calling .ToList on this method gets you the desired List(Of String)
We will loop through the length of the list in a for loop. We subtract one because indexes start at zero.
To get the random index we call .Next on our instance of the Random class that was declared outside the method (a form level variable) The .Next method is inclusive of the first variable and exclusive of the second. I used a variable to store the original value of lines.Count because this value will change in the loop and it would mess with for loop if we used lines.Count -1 directly in the To portion of the For.
Once we get the random index we add that line to the TextBox and remove it from the list.
Private Sub ShuffleNames()
Dim index As Integer
Dim lines = File.ReadAllLines("C:\Users\xxx\Desktop\names.txt").ToList
Dim loopLimit = lines.Count - 1
For i = 0 To loopLimit
index = rnd.Next(0, lines.Count)
TextBox1.AppendText(lines(index).Trim & Environment.NewLine)
lines.RemoveAt(index)
Next
End Sub

Visual Basic, new to coding. Need to make a list of 100 integers create a shuffled list of 70 results

I'm new to coding and I have got firmly stuck on this.
I've created a list in Visual Basic with
Dim integerStable As New List(Of Integer)()
integerStable.Add(0)
integerStable.Add(1)
integerStable.Add(2)
'through to integerStable.Add(99)
I'm trying to keep this list (it can be shuffled as long as all numbers stay in the list in general) and create a 2nd list where it only has 70 results from that shuffle.
I need that list, so I can call on it to perform some tasks for me later.
Can anyone help me work out how to do this? Remember I'm new to coding, but I'll try to follow along.
One of the most efficient ways to create your list would be as follows:
Dim integerStable As New List(Of Integer)
For i = 1 To 100
integerStable.Add(i)
Next
That at least should save you a lot of typing!!
You could also do the following:
Dim integerStable As New List(Of Integer)
Dim i As Integer
While i <= 100
integerStable.Add(i)
i += 1
End While
**Note though that the latter example will give you 101 items as integer is initially set to 0 **
You also need to remember that the list will be 'indexed' from 0 NOT 1 which is an important thing to remember when it comes to manipulating the items with it.
It can be much simpler.
Private Shared PRNG As New Random
' 100 numbers starting at zero, in random order
Private listOnum As List(Of Integer) = Enumerable.Range(0, 100).OrderBy(Function(x) PRNG.Next).ToList
' list of 70 numbers from list of 100
Private list70 As List(Of Integer) = listOnum.Take(70).ToList
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'did it work?
Dim ct As Integer = 1
For Each n As Integer In list70
Debug.WriteLine("{0}. {1,3}", ct, n)
ct += 1
Next
End Sub
Enumerable.Range takes two arguments. The first is a start number and the second is a count, so in the example it created a list that started at 0 and ended with 99, 100 items. The OrderBy just sorted that list by random numbers.
list70 is created by taking the first 70 items from listOnum.
The Random, PRNG, is created that way so that there is only ONE random that is only initialized once. You can find many problems associated with the incorrect initialization of Random.
edit: Slightly different approach.
Private Shared PRNG As New Random
' 100 numbers starting at zero
Private listOnum As List(Of Integer) = Enumerable.Range(0, 100).ToList
' list of 70 random numbers from list of 100
Private list70 As List(Of Integer) = listOnum.OrderBy(Function(x) PRNG.Next).Take(70).ToList
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'did it work?
Dim ct As Integer = 1
For Each n As Integer In list70
Debug.WriteLine("{0}. {1,3}", ct, n)
ct += 1
Next
'recreate list of 70
list70 = listOnum.OrderBy(Function(x) PRNG.Next).Take(70).ToList
End Sub

Select any random string from a list

How can I select any random string from a given list of strings? Example:
List1: banana, apple, pineapple, mango, dragon-fruit
List2: 10.2.0.212, 10.4.0.221, 10.2.0.223
When I call some function like randomize(List1) = somevar then it will just take any string from that particular list. The result in somevar will be totally random. How can it be done? Thank you very much :)
Use Random
Dim rnd = new Random()
Dim randomFruit = List1(rnd.Next(0, List1.Count))
Note that you have to reuse the random instance if you want to execute this code in a loop. Otherwise the values would be repeating since random is initialized with the current timestamp.
So this works:
Dim rnd = new Random()
For i As Int32 = 1 To 10
Dim randomFruit = List1(rnd.Next(0, List1.Count))
Console.WriteLine(randomFruit)
Next
since always the same random instance is used.
But this won't work:
For i As Int32 = 1 To 10
Dim rnd = new Random()
Dim randomFruit = List1(rnd.Next(0, List1.Count))
Console.WriteLine(randomFruit)
Next
Create a List of Strings.
Create a random number generator: Random class
Call Random number generator's NextInt() method with List.Count as the upper bound.
Return List[NextInt(List.count)].
Job done :)
Generate a random number between 1 and the size of the list, and use that as an index?
Try this:
Public Function randomize(ByVal lst As ICollection) As Object
Dim rdm As New Random()
Dim auxLst As New List(Of Object)(lst)
Return auxLst(rdm.Next(0, lst.Count))
End Function
Or just for string lists:
Public Function randomize(ByVal lst As ICollection(Of String)) As String
Dim rdm As New Random()
Dim auxLst As New List(Of String)(lst)
Return auxLst(rdm.Next(0, lst.Count))
End Function
You could try this, this is a simple loop to pick every item from a list, but in a random manner:
Dim Rand As New Random
For C = 0 to LIST.Count - 1 'Replace LIST with the collection name
Dim RandomItem As STRING = LIST(Rand.Next(0, LIST.Count - 1)) 'Change the item type if needed (STRING)
'' YOUR CODE HERE TO USE THE VARIABLE NewItem ''
Next

Is there an easy way to randomize a list in VB.NET?

I have a list of type System.IO.FileInfo, and I would like to randomize the list. I thought I remember seeing something like list.randomize() a little while back but I cannot find where I may have seen that.
My first foray into this yielded me with this function:
Private Shared Sub GetRandom(ByVal oMax As Integer, ByRef currentVals As List(Of Integer))
Dim oRand As New Random(Now.Millisecond)
Dim oTemp As Integer = -1
Do Until currentVals.Count = IMG_COUNT
oTemp = oRand.Next(1, oMax)
If Not currentVals.Contains(oTemp) Then currentVals.Add(oTemp)
Loop
End Sub
I send it the max val I want it to iterate up to, and a reference to the list I want the randomized content in. The variable IMG_COUNT is set farther up in the script, designating how many random images I want displayed.
Thanks guys, I appreciate it :D
Check out the Fisher-Yates shuffle algorithm here: http://en.wikipedia.org/wiki/Knuth_shuffle
with a more concise discussion by this site's chief overlord here:
http://www.codinghorror.com/blog/archives/001015.html
There is a simple C# implementation in the blog entry that should be real easy to change to VB.NET
I've extended the List class with the following Randomize() function to use the Fisher-Yates shuffle algorithm:
''' <summary>
''' Randomizes the contents of the list using Fisher–Yates shuffle (a.k.a. Knuth shuffle).
''' </summary>
''' <typeparam name="T"></typeparam>
''' <param name="list"></param>
''' <returns>Randomized result</returns>
''' <remarks></remarks>
<Extension()>
Function Randomize(Of T)(ByVal list As List(Of T)) As List(Of T)
Dim rand As New Random()
Dim temp As T
Dim indexRand As Integer
Dim indexLast As Integer = list.Count - 1
For index As Integer = 0 To indexLast
indexRand = rand.Next(index, indexLast)
temp = list(indexRand)
list(indexRand) = list(index)
list(index) = temp
Next index
Return list
End Function
Build a Comparer:
Public Class Randomizer(Of T)
Implements IComparer(Of T)
''// Ensures different instances are sorted in different orders
Private Shared Salter As New Random() ''// only as random as your seed
Private Salt As Integer
Public Sub New()
Salt = Salter.Next(Integer.MinValue, Integer.MaxValue)
End Sub
Private Shared sha As New SHA1CryptoServiceProvider()
Private Function HashNSalt(ByVal x As Integer) As Integer
Dim b() As Byte = sha.ComputeHash(BitConverter.GetBytes(x))
Dim r As Integer = 0
For i As Integer = 0 To b.Length - 1 Step 4
r = r Xor BitConverter.ToInt32(b, i)
Next
Return r Xor Salt
End Function
Public Function Compare(x As T, y As T) As Integer _
Implements IComparer(Of T).Compare
Return HashNSalt(x.GetHashCode()).CompareTo(HashNSalt(y.GetHashCode()))
End Function
End Class
Use it like this, assuming you mean a generic List(Of FileInfo):
list.Sort(New Randomizer(Of IO.FileInfo)())
You can also use a closure to make the random value 'sticky' and then just use linq's .OrderBy() on that (C# this time, because the VB lambda syntax is ugly):
list = list.OrderBy(a => Guid.NewGuid()).ToList();
Explained here, along with why it might not even be as fast as real shuffle:
http://www.codinghorror.com/blog/archives/001008.html?r=31644
There are several reasonable methods of shuffling.
One has already been mentioned. (The Knuth Shuffle.)
Another method would be to assign a "weight" to each element and sort the list according to that "weight." This method is possible but would be unweildy because you cannot inherit from FileInfo.
One final method would be to randomly select an element in the original list and add it to a new list. Of course, that is, if you don't mind creating a new list. (Haven't tested this code...)
Dim rnd As New Random
Dim lstOriginal As New List(Of FileInfo)
Dim lstNew As New List(Of FileInfo)
While lstOriginal.Count > 0
Dim idx As Integer = rnd.Next(0, lstOriginal.Count - 1)
lstNew.Add(lstOriginal(idx))
lstOriginal.RemoveAt(idx)
End While
You could also implement a shuffle, many ways to do this, the simplest is randomly pick a item and insert it into a new location a bunch of times.
If you have the number of elements then a pseudo-random method can be used whereby you choose the first element at random (e.g. using the inbuilt random number function) then add a prime and take the remainder after division by the number of values. e.g. for a list of 10 you could do i = (i + prime) % 10 to generated indices i from some starting value. As long as the prime is greater than the number of values in the list then you create a sequence which runs through all of the numbers 0...n where n is the number of values - 1, but in a pseudorandom order.
Dim oRand As New Random() 'do not seed!!!!
Private Sub GetRandom(ByRef currentVals As List(Of Integer))
Dim i As New List(Of Integer), j As Integer
For x As Integer = 0 To currentVals.Count - 1
j = oRand.Next(0, currentVals.Count)
i.Add(currentVals(j))
currentVals.RemoveAt(j)
Next
currentVals = i
End Sub
You could create custom comparer that just returns a random number, then sort the list using this comparer. It could be horribly inefficient and cause an almost infinite loop, but might be worth a try.