Generation of random string based on two characters in VB.NET - vb.net

I'm trying to create a predefined number of rows, each having a predefined number of characters. The characters allowed are only 0's and 1's and are randomly generated.
I have achieved this with this code:
Dim _allowedChars As String = "01"
Dim randomNumber As New Random()
Dim chars As List(Of Char) = New List(Of Char)
Dim allowedCharCount As Integer = _allowedChars.Length
For o As Integer = 0 To rows - 1
For a As Integer = 0 To rowCharacters - 1
chars.Add(_allowedChars.Chars(CInt(Fix((_allowedChars.Length) * randomNumber.NextDouble()))))
Next a
For a As Integer = 0 To chars.Count - 1
'results for each row go here in a textbox line
Next a
chars = New List(Of Char)
'row o finished, new line and go for next row
Next o
This works great, an example output of setting 5 rows and 5 chars (only consisted of randomly generated 0's or 1's) is shown here:
11101
00000
11011
00000
01011
I now want to add an extra twist to it: specify the minimum percentage of 1's for each row, i.e. "even though randomly distributed, each row should have at least 20% of 1's". The percentage is based on the length of the chars in each row (variable rowCharacters in the code).
Anyone who could help me out on this one?
Thanks!

Dim _allowedChars As String = "01"
Dim randomNumber As New Random()
Dim chars As List(Of Char) = New List(Of Char)
Dim allowedCharCount As Integer = _allowedChars.Length
'
For o As Integer = 0 To rows - 1
Do
For a As Integer = 0 To rowCharacters - 1
chars.Add(_allowedChars.Chars(CInt(Fix((_allowedChars.Length) * randomNumber.NextDouble()))))
Next a
For a As Integer = 0 To chars.Count - 1
'results for each row go here in a textbox line
Next a
chars = New List(Of Char)
'row o finished, new line and go for next row
Loop Until IsValidPercent(chars, 20)
Next o
Function IsValidPercent(chars As List(Of Char), ReqPercentage as integer) as boolean
'
Dim counter as integer = 0
Dim qtyones as integer = 0
'
IsValidPercent = False
for counter = 0 to chars.count -1
if chars(counter) = "1" Then qtyones = qtyones + 1
next
if qtyones >= ((chars.count/100)*ReqPercentage) Then IsValidPercent = True
'
End Function

Related

Unable to edit array data in For Each Loop

Like title, running this code shows an array with all 0 values in it.
I have tried using integer array too but I can't
Dim woohoo(9) As String
Dim count As Integer = 2
For Each number As String In woohoo
number = CStr(count)
count += 2
Next
For Each number As Integer In woohoo
Console.WriteLine(number)
Next
2,4,6,8,10...20
You need to do this to SET the values of an array:
Dim wooho(9) As Integer
Dim count As Integer = 2
For i As Integer = 0 To wooho.Count - 1
wooho(i) = count
count += 2
Console.WriteLine(wooho(i))
Next
And this to GET the values:
For Each number As Integer In wooho
Console.WriteLine(number)
Next
I suggest using a list of Integers for this.
Try this:
Dim woohoo As New List (Of Integer)
Dim count As Integer = 2
For i As Integer = 0 To 9
woohoo.Items.Add (count)
count += 2
Next
For Each number As Integer In woohoo
Console.WriteLine(CStr(number))
Next

Count a specific string in a multiline textbox (VB.Net)

I very much want to count the values in a multiline textbox each time each value appears in descending order> in ascending order. I tried a lot but nothing works as it should. (VB.Net)
Textbox1.Lines
2
3
2
2
4
7
7
7
28
28
Expected Output: Textbox2.Lines
2 = Count = 3
7 = Count = 3
28 = Count = 2
3 = Count = 1
4 = Count = 1
What i try and dind't worked.
#1
Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
Dim cnt As Integer = 0
For Each c As Char In value
If c = ch Then
cnt += 1
End If
Next
Return cnt
End Function
#2
Dim a As String = "this is test"
Dim pattern As String = "t"
Dim ex As New System.Text.RegularExpressions.Regex(pattern)
Dim m As System.Text.RegularExpressions.MatchCollection
m = ex.Matches(a)
MsgBox(m.Count.ToString())
#3
Public Shared Function StrCounter(str As String, CountStr As String) As Integer
Dim Ctr As Integer = 0
Dim Ptr As Integer = 1
While InStr(Ptr, str, CountStr) > 0
Ptr = InStr(Ptr, str, CountStr) + Len(CountStr)
Ctr += 1
End While
Return Ctr
End Function
You need to remember which strings have already appeared and then count them. To do that, you can use a dictionary.
Dim dict_strCount As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)()
' Run over each line in the input
For Each line As String In tb_yourTextBox.Text.Lines
' Check if we have already counted the string in this line
If dict_strCount.ContainsKey(line) Then
dict_strCount(line) += 1 ' if so, increment that count
Else
dict_strCount.Add(line, 1) ' if not, add it to the dictionary (with count of 1)
End If
Next
tb_yourOutputTextBox.Text = String.Empty ' clear the output
' run over all the elements in the dictionary in ascending order by value
' and output to the output textbox
For Each kvp As KeyValuePair(Of String, Integer) In dict_strCount.OrderBy(Function(x) x.Value)
tb_yourOutputTextBox.Text += kvp.Key & ": " & kvp.Value.ToString() & vbNewLine
Next
You may test it here

Doubles will not output in DataGridView

I have a DataGridView that I want to fill with values that are Doubles. The DataGridView filled fine when the values were strings, but now it outputs System.Double[] in the first column and nothing in any other column. I know the conversion is working because I can print the double values to the console. How do I format all columns programmatically? (I don't want to use the designer)
My code:
Dim cols() as String = {"col1", "col2", "col3"} ' this goes on for 33 cols
Dim currentRow As String()
Dim row() As Double
Dim c As Integer
DataGridView1.Rows.Clear()
DataGridView1.ReadOnly = True
DataGridView1.DefaultCellStyle.Format = "G"
DataGridView1.ColumnCount = 33
For c = 0 To (cols.Length - 1)
DataGridView1.Columns(c).Name = cols(c)
Next
While Not at EndOfFile ' This line and the next are semi-pseudocode, but it's the same idea
read/parse line into currentRow
Dim x As Integer
For x = 0 To (currentRow.Length - 1)
ReDim Preserve row(x)
Double.TryParse(currentRow(x), row(x))
Next
With Me.DataGridView1.Rows
.Add(row)
End With
Screenshot of the output:
You can first add the row to the grid, then loop through your array to add the information to each cell.
Dim i as integer = DataGridView1.Rows.Add
For x As Integer = 0 to row.Count - 1
DataGridView1.Rows(i).Cells(x).Value = row(x)
Next

vb.net generate random number and string

I want to generate a random number of 6 intergers in vb.net which should be number and also some times alphanumerice.Like ist 4 or 5 numbers should be numbers and next should be alphnumeric.I created both numbers separatedly.like this
Public Function rand() As String
'Number
Dim rng As Random = New Random
Dim number As Integer = rng.Next(1, 1000000)
Dim digits As String = number.ToString("000000")
'Alphnumeric
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim r As New Random
Dim sb As New StringBuilder
For i As Integer = 1 To 5
Dim idx As Integer = r.Next(0, 35)
sb.Append(s.Substring(idx, 1))
Next
End Function
Now Any One Give Me Idea that in this function can i return number and some times string or may b a single instances which create both numbers and strings.
The first problem to solve is the random number generator. You should use only one instance and not multiple instances that gives back the same sequence if called in short time distance. Then it is
difficult to say what 'something' means in your requirements, but supposing you are fine with rougly 70% numbers and 30% a mix of numbers and strings then you call the random generator to decide for a sequence of only numbers or a mixed one. Based on the output of the random selection of the sequence build from the appropriate string
' A global unique random generator'
Dim rng As Random = New Random
Sub Main
Console.WriteLine(rand())
Console.WriteLine(rand())
Console.WriteLine(rand())
Console.WriteLine(rand())
End Sub
Public Function rand() As String
Dim sb As New StringBuilder
' Selection of pure numbers sequence or mixed one
Dim pureNumbers = rng.Next(1,11)
if pureNumbers < 7 then
' Generate a sequence of only digits
Dim number As Integer = rng.Next(1, 1000000)
Dim digits As String = number.ToString("000000")
For i As Integer = 1 To 6
Dim idx As Integer = rng.Next(0, digits.Length)
sb.Append(digits.Substring(idx, 1))
Next
else
' Generate a sequence of digits and letters
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
For i As Integer = 1 To 6
Dim idx As Integer = rng.Next(0, 36)
sb.Append(s.Substring(idx, 1))
Next
End if
return sb.ToString()
End Function

generate random string

well i know that there are a lot of these threads but im new to vb.net yet i cant edit the sources given to make what i really want
so i want a function that will generate random strings which will contain from 15-32 characters each and each of them will have the following chars ( not all at the same string but some of them ) :
A-Z
a-z
0-9
here is my code so far
Functon RandomString()
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim r As New Random
Dim sb As New StringBuilder
For i As Integer = 1 To 8
Dim idx As Integer = r.Next(0, 35)
sb.Append(s.Substring(idx, 1))
Next
return sb.ToString()
End Function
Change the string to include the a-z characters:
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Change the loop to create a random number of characters:
Dim cnt As Integer = r.Next(15, 33)
For i As Integer = 1 To cnt
Note that the upper boundary in the Next method is exclusive, so Next(15, 33) gives you a value that can range from 15 to 32.
Use the length of the string to pick a character from it:
Dim idx As Integer = r.Next(0, s.Length)
As you are going to create random strings, and not a single random string, you should not create the random number generator inside the function. If you call the function twice too close in time, you would end up with the same random string, as the random generator is seeded using the system clock. So, you should send the random generator in to the function:
Function RandomString(r As Random)
So, all in all:
Function RandomString(r As Random)
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Dim sb As New StringBuilder
Dim cnt As Integer = r.Next(15, 33)
For i As Integer = 1 To cnt
Dim idx As Integer = r.Next(0, s.Length)
sb.Append(s.Substring(idx, 1))
Next
return sb.ToString()
End Function
Usage example:
Dim r As New Random
Dim strings As New List<string>()
For i As Integer = 1 To 10
strings.Add(RandomString(r))
Next
Try something like this:-
stringToReturn&= Guid.NewGuid.ToString().replace("-","")
You can also check this:-
Sub Main()
Dim KeyGen As RandomKeyGenerator
Dim NumKeys As Integer
Dim i_Keys As Integer
Dim RandomKey As String
''' MODIFY THIS TO GET MORE KEYS - LAITH - 27/07/2005 22:48:30 -
NumKeys = 20
KeyGen = New RandomKeyGenerator
KeyGen.KeyLetters = "abcdefghijklmnopqrstuvwxyz"
KeyGen.KeyNumbers = "0123456789"
KeyGen.KeyChars = 12
For i_Keys = 1 To NumKeys
RandomKey = KeyGen.Generate()
Console.WriteLine(RandomKey)
Next
Console.WriteLine("Press any key to exit...")
Console.Read()
End Sub
Using your function as a guide, I modified it to:
Randomize the length (between minChar & maxCharacters)
Randomize the string produced each time (by using the static Random)
Code:
Function RandomString(minCharacters As Integer, maxCharacters As Integer)
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Static r As New Random
Dim chactersInString As Integer = r.Next(minCharacters, maxCharacters)
Dim sb As New StringBuilder
For i As Integer = 1 To chactersInString
Dim idx As Integer = r.Next(0, s.Length)
sb.Append(s.Substring(idx, 1))
Next
Return sb.ToString()
End Function
Try this out:
Private Function RandomString(ByRef Length As String) As String
Dim str As String = Nothing
Dim rnd As New Random
For i As Integer = 0 To Length
Dim chrInt As Integer = 0
Do
chrInt = rnd.Next(30, 122)
If (chrInt >= 48 And chrInt <= 57) Or (chrInt >= 65 And chrInt <= 90) Or (chrInt >= 97 And chrInt <= 122) Then
Exit Do
End If
Loop
str &= Chr(chrInt)
Next
Return str
End Function
You need to change the line For i As Integer = 1 To 8 to For i As Integer = 1 To ? where ? is the number of characters long the string should be. This changes the number of times it repeats the code below so more characters are appended to the string.
Dim idx As Integer = r.Next(0, 35)
sb.Append(s.Substring(idx, 1))
My $.02
Dim prng As New Random
Const minCH As Integer = 15 'minimum chars in random string
Const maxCH As Integer = 35 'maximum chars in random string
'valid chars in random string
Const randCH As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Private Function RandomString() As String
Dim sb As New System.Text.StringBuilder
For i As Integer = 1 To prng.Next(minCH, maxCH + 1)
sb.Append(randCH.Substring(prng.Next(0, randCH.Length), 1))
Next
Return sb.ToString()
End Function
please note that the
r.Next(0, 35)
tend to hang and show the same result Not sure whay; better to use
CInt(Math.Ceiling(Rnd() * N)) + 1
see it here Random integer in VB.NET
I beefed up Nathan Koop's function for my own needs, and thought I'd share.
I added:
Ability to add Prepended and Appended text to the random string
Ability to choose the casing of the allowed characters (letters)
Ability to choose to include/exclude numbers to the allowed characters
NOTE: If strictly looking for an exact length string while also adding pre/appended strings you'll need to deal with that; I left out any logic to handle that.
Example Usages:
' Straight call for a random string of 20 characters
' All Caps + Numbers
String_Random(20, 20, String.Empty, String.Empty, 1, True)
' Call for a 30 char string with prepended string
' Lowercase, no numbers
String_Random(30, 30, "Hey_Now_", String.Empty, 2, False)
' Call for a 15 char string with appended string
' Case insensitive + Numbers
String_Random(15, 15, String.Empty, "_howdy", 3, True)
.
Public Function String_Random(
intMinLength As Integer,
intMaxLength As Integer,
strPrepend As String,
strAppend As String,
intCase As Integer,
bIncludeDigits As Boolean) As String
' Allowed characters variable
Dim s As String = String.Empty
' Set the variable to user's choice of allowed characters
Select Case intCase
Case 1
' Uppercase
s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Case 2
' Lowercase
s = "abcdefghijklmnopqrstuvwxyz"
Case Else
' Case Insensitive + Numbers
s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
End Select
' Add numbers to the allowed characters if user chose so
If bIncludeDigits = True Then s &= "0123456789"
Static r As New Random
Dim chactersInString As Integer = r.Next(intMinLength, intMaxLength)
Dim sb As New StringBuilder
' Add the prepend string if one was passed
If String.IsNullOrEmpty(strPrepend) = False Then sb.Append(strPrepend)
For i As Integer = 1 To chactersInString
Dim idx As Integer = r.Next(0, s.Length)
sb.Append(s.Substring(idx, 1))
Next
' Add the append string if one was passed
If String.IsNullOrEmpty(strAppend) = False Then sb.Append(strAppend)
Return sb.ToString()
End Function