VB.NET中基于两个字符的随机字符串生成
我试图创建一个预定义的行数,每个行都有预定义的字符数。允许的字符仅为0和1,并且是随机生成的 我通过以下代码实现了这一点:VB.NET中基于两个字符的随机字符串生成,vb.net,.net-4.0,Vb.net,.net 4.0,我试图创建一个预定义的行数,每个行都有预定义的字符数。允许的字符仅为0和1,并且是随机生成的 我通过以下代码实现了这一点: 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
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
这非常有效,下面显示了设置5行和5个字符(仅由随机生成的0或1组成)的示例输出:
11101
00000
11011
00000
01011
现在我想给它添加一个额外的转折点:指定每行1的最小百分比,即“即使随机分布,每行至少应有20%的1”。百分比基于每行中字符的长度(代码中的可变rowCharacters)
有谁能帮我解决这个问题吗
谢谢
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