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)
Related
I have a list of numbers with anywhere from 1 to 5 digits (The numbers are values in a DataGridView column). There is only one of the numbers that is unique. All of the other numbers are duplicated at least once. I need to get the one unique number that is not duplicated.
There are many good articles on line which skirt around my task, some using linq but none look for the one only item. I found the code shown below but I don't understand what the Function(X) is.
Dim distinct = mynumber.DistinctBy(Function(X) X.muNumber).ToList
I used a Linq query on a list of numbers and called .ToList on the query so it would result in the more friendly List(Of Integer) rather than an IEnumerable. Since you seemed sure that you only had one unique value I printed the first item of the list to the immediate window. If you were to have more unique values you could just loop through unique.
I am sure this is not the most efficient way to do this but it should work.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lstNumbers As New List(Of Integer) From {1, 5, 77, 1, 32, 5, 77}
Dim unique = (From i In lstNumbers
Let ct = (From i2 In lstNumbers Where i2 = i Select i2).Count
Where ct = 1
Select i).ToList
Debug.Print(unique(0).ToString)
End Sub
EDIT
As per OP's comment - How to use a string of numbers.
'This line won't compile unless you put quotes around it.
Dim nums As String = "1,2, 3, 4, 1, 2, 3, 4, 5"
'There are a few steps to change this string into a list of numbers.
'First get an array of strings
Dim splitNums = nums.Split(","c) 'This overload of Split takes a Char array. The c tells it that this is a char not a string.
'Each of the strings in the array are trimmed of any leading or trailing spaces.
'Then the string is converted to an Integer
'Finally the whole query is changed to a list
Dim lstNumbers = (From i In splitNums
Select CInt(i.Trim)).ToList
'and now lstNumbers is indeed a list of Integers which can be used in the code.
EDIT 2
To see if there are more than one unique numbers use a For Each loop.
For Each i In unique
TextBox1.Text &= i.ToString & ", "
Next
I'm very new to VB.NET language so there are some things I'm still learning and I need some help here. So I'd appreciate any guidance.
I'm making an XOR encryption app where there's a key, input and output. The flow is like this: Key XOR Input and the result will appear as the output. I managed to successfully come out with workable codes for that part though.
However, right now, I need to make a continuation from that part. I need the output to come out within the ASCII range of 33 - 126 (DEC) only.
I have not done anything much in terms of coding as I can't seem to find the right guide. Additionally, I don't really know where to start except that some mathematical logic (MOD) is involved here.
So any pointers? Thank you.
I am using Visual Studio (2017) and here's my code:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim key As String
Dim input As String
Dim output As String
Dim keyCounter As Integer = 0
Dim length As Integer
key = TextBox1.Text
input = TextBox2.Text
length = key.Length
For Each letter As Char In input
output = output & Chr(Asc(letter) Xor Asc(key.Chars(keyCounter)))
If keyCounter = length - 1 Then
keyCounter = 0
Else
keyCounter += 1
End If
Next
TextBox3.Text = output
End Sub
End Class
The math is quite simple. To constrain a number within a range using modulo start by calculating how many numbers there are in the range (inclusive):
126 - 33 + 1 = 94
Then take your value and calculate the modulo using the length, and add the lower value of the range (33) to make it go from 33-126 instead of 0-93:
(value Mod 94) + 33
Alternatively, if you need numbers that already are in the range 33-126 to not change you can subtract the lower value first:
((value - 33) Mod 94) + 33
I am trying to write a program that will allow a user to generate a random list of names. I have a gridview of names from a SQL Db when the form launches. Is it possible to generate a random list from the names in the gridview or does that have to come from another Sql Connection string and reference different parameters? I was trying to display random names from the gridview to a listbox. Thank you.
Here is the code that I have been trying to experiment with:
Private Sub btnDraw_Click(sender As Object, e As EventArgs) Handles btnDraw.Click
Dim listCount As Integer
Dim i As Integer = 0
Dim rnd As New Random
Dim listselection As Integer
listCount = grdEmployees.
Do While i < CInt(grdEmployees.Text)
'randomize selection
listselection = rnd.Next(0, grdEmployees.Items.Count)
lstSelected.Items.Add(grdEmployees.Items(listselection))
grdEmployees.Items.RemoveAt(listselection)
'increment i
i += 1
Loop
txtQuantity.Text = String.Empty 'Clears box after entry
End Sub
You could do it through your SQL query:
SELECT TOP 25 SomeField FROM SomeTable ORDER BY RAND()
Or through your managed code. Which is best depends on the size of the table and where you want the sorting to be done. If you prefer to sort on the server, or locally.
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
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