I have some VB code that gives me a random number, 1 between 20 (X). However, within 20 attempts, I will get the same number twice. How can I get a sequence of random numbers without any of them repeating? I basically want 1-20 to show up up in a random order if I click a button 20 times.
Randomize()
' Gen random value
value = CInt(Int((X.Count * Rnd())))
If value = OldValue Then
Do While value = OldValue
value = CInt(Int((X.Count * Rnd())))
Loop
End If
For 1 to 20, use a data structure like a LinkedList which holds numbers 1 to 20. Choose an index from 1 to 20 at random, take the number at that index, then pop out the number in that location of the LinkedList. Each successive iteration will choose an index from 1 to 19, pop, then 1 to 18, pop, etc. until you are left with index 1 to 1 and the last item is the last random number. Sorry for no code but you should get it.
The concept is, you have to add the generated random number into a list, and before adding it into the list, make sure that the new number is not contains in it. Try this code,
Dim xGenerator As System.Random = New System.Random()
Dim xTemp As Integer = 0
Dim xRndNo As New List(Of Integer)
While Not xRndNo.Count = 20
xTemp = xGenerator.Next(1, 21)
If xRndNo.Contains(xTemp) Then
Continue While
Else
xRndNo.Add(xTemp)
End If
End While
[Note: Tested with IDE]
for that purpose, you need to store all previous generated number, not just one, as u did in OldValue named variable. so, store all previously generated numbers somewhere (list). and compare the newly generated number with all those in list, inside ur while loop, and keep generating numbers, while number is not equal to any of one in list..
Add the numbers to a list and then pick them in a random order, deleting them as they are picked.
Dim prng As New Random
Dim randno As New List(Of Integer)
Private Sub Button1_Click(sender As Object, _
e As EventArgs) Handles Button1.Click
If randno.Count = 0 Then
Debug.WriteLine("new")
randno = Enumerable.Range(1, 20).ToList 'add 1 to 20 to list
End If
Dim idx As Integer = prng.Next(0, randno.Count) 'pick a number
Debug.WriteLine(randno(idx)) 'show it
randno.RemoveAt(idx) 'remove it
End Sub
Related
I'm trying to generate 5 random numbers from 1-99 and display them in a ListBox. Can someone tell me where I'm going wrong? Right now my code is displaying all 99 numbers in the ListBox, but I only want 5 of them to display. Here is the code:
'list to store numbers
Dim numbers As New List(Of Integer)
'add desired numbers to list
For count As Integer = 1 To 99
numbers.Add(count)
Next
Dim Rnd As New Random
Dim SB As New System.Text.StringBuilder
Dim Temp As Integer
'select a random number from the list, add to listbox and remove it so it can't be selected again
For count As Integer = 0 To numbers.Count - 1
Temp = Rnd.Next(0, numbers.Count)
SB.Append(numbers(Temp) & " ")
ListBox2.Items.Add(numbers(Temp))
numbers.RemoveAt(Temp)
Next
Replace
For count As Integer = 0 To numbers.Count - 1
With
For count As Integer = 1 To 5
The above will work but, You need to add count just after your next statement as well. I recommend checking into learning more about loops as well. Clearly Visual Basic 2012 is great for that.
I am trying to make a simple keygen app (hoping to evolve it later) and am running into a problem with naming my variables:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim keylength As Double = TrackBar1.Value
Dim baseloop As Double = 1
Dim charpos As Double = 1
Do While baseloop < keylength
Randomize()
Dim name As String = "num" & charpos
Dim (name) As Integer = CInt(Int((62 * Rnd()) + 1))
'I would like to name this variable the current value of the variable "name".
baseloop = baseloop + 1
charpos = charpos + 1
Loop
End Sub
The end result should be random doubles (as many as TrackBar1.Value) containing random doubles from 1-62 and named num1, num2, num3, etc.... Then I can replace all the 1s with a, 2 with b, etc etc....
Thanks for your help
As has been said, what you claim to want to do is not possible. You can't declare an arbitrary number of variables at run time because variables are declared at design time. If you want to store an arbitrary number of values then you declare one variable and assign to that variable an array or collection of some sort. An array can be created with any size at run time and collections can grow to an arbitrary size at run time. Basically, what you're trying to do is outright wrong.
If you want an arbitrary number of Double values then create an array with a sized based on a user-defined value and then simply loop to populate it, e.g.
Dim values(userDefinedValue - 1) As Double
For i = 0 To values.GetUpperBound(0)
'...
Next
You then access the values by index. The first value is at index 0, the second at index 1, ..., the last at index GetUpperBound(0).
I am very new to linq and would like to do the following. Create an array of 11 elements (that works ok) contains random number from 20 to 35 without duplicates. The code I have only gives me random number from 0 to 9.
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim r As New Random
'Create an array of exclusive numbers from 0 to 10
Dim exclusive_numbers() As Integer = Enumerable.Range(0, 10).OrderBy(Function(n) r.Next(20, 35)).ToArray
For x = 0 To 10
MsgBox (exclusive_numbers(x).ToString )
Next
End Sub
I would really like to make this work, but I fear it is over my head at this time. Any help, ideas or working code would be appreciated.
thanks
george
Dim r As New Random()
Dim exclusive_numbers As Integer() = Enumerable.Range(20, 16).OrderBy(Function(n) r.Next).Take(11).ToArray()
Will generate 11 random numbers in the range of 20->20+16-1 => 20=>35
The reason yours is giving 0-9 still is because that is what you are specifying the Enumberable Range of numbers to be (start at 0, generate 10 integers, then randomly sort)
#JoelCoehoorn metions below that order by Random.Next() could cause an Exception. Another way to do this would be to order by a Guid.NewGuid().
Enumerable.Range(20, 16).OrderBy(Function(t) Guid.NewGuid()).Take(11)
I'm running a search query that pulls the search string from one text box, then searches a listbox for the string and displays the results in a second listbox. I would like to define the number of items that it returns based on a second text box. So far I am able to get all list items with be given string to show in the second box. But I have yet to get it to limit the search to 1 item etc. The functional code I've used to show all results is:
Private Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click
lstResults.Items.Clear()
If txtSearch.Text.Length > 0 Then
For index As Integer = 0 To lstCountries.Items.Count - 1
Dim txt = lstCountries.Items(index).ToString()
If txt.StartsWith(txtSearch.Text, StringComparison.CurrentCultureIgnoreCase) Then
lstResults.Items.Add(txt)
End If
Next
End If
I've tried using while txtnumber.text > 1 then ahead of this but seem to have created a loop. Any ideas as to what I'm missing?
The datasource is going to have the final say on how many results there are. If the user specifies 3 and there are only 2 in the source, thats all you will get. Something like this will move the results from one to the other until the max is found:
Dim Max as integer = Convert.Toint32(txtNumber.Text)
Dim Count as integer = 0
lstResults.Items.Clear()
For index As Integer = 0 To lstCountries.Items.Count - 1
if lstCountries.Items(index).StartsWith(txtSearch.Text, StringComparison.CurrentCultureIgnoreCase) Then
lstResults.Items.Add(lstCountries.Items(index))
count += 1
end if
' exit the loop if we found enough
If count>= Max Then
Exit For
End If
Next
If the listbox just contains text (strings) then you do not need the ToString: lstCountries.Items(index).StartsWith(strSearch). Basically, you need to exit the loop once the user desired number have been found OR if you run out of data...if I understood right. while txtnumber.text > 1 would not work because textboxes contain strings not numerics (23 is not the same as "23").
The LINQ extensions would work well here as well:
lstResults.Items.AddRange((From item In lstCountries.Items
Let strItem As String = item.ToString
Where strItem.StartsWith(txtSearch.Text, StringComparison.CurrentCultureIgnoreCase)
Select strItem).Take(Integer.Parse(txtnumber.Text)).ToArray)
This assumes that all your data has already been validated.
So i am trying to make a search bot that uses random words. I am using an increment value with Minimum of 2 and a Maximum of 30 for the number of searches to do at a time.
I was thinking something like this but it also seems like it would not be as good since it would not really generate a random string which would be a lot better:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim SE As String
SE = NumericUpDown1.Value
Select Case SE
Case "2"
End Select
End Sub
If anybody could help me It would be greatly appreciated.
You can use the Random class and it's method Next to create random numbers.
Dim rnd As New Random()
Dim SE As String = rnd.Next(2, 31).ToString()
Note that the random number generation starts from a seed value. If the same
seed is used repeatedly, the same series of numbers is generated.
So if you want to use a loop, you should not create the random instance in the loop but outside of it.
However, i'm not sure what kind of words you want to create. I doubt that you want numeric strings between "2" and"30" even if your code suggests it.
Update according to your comment
The 2 and 30 are how many searches to do at a time, i want to
randomize the word(s) out of
lets say a list of 60-70 words
So i assume that you want a random number(between 2-30)of random words from a list of strings:
Dim words = {"word 1", "word 2", "word 3", ".....", "word 60"}
Dim rnd As New Random()
Dim howMany As Int32 = rnd.Next(2, 31)
Dim randomWords As New List(Of String)
For i As Int32 = 1 To howMany
Dim nextRandomIndex = rnd.Next(0, words.Count)
randomWords.Add(words(nextRandomIndex))
Next