2013-04-13 182 views
0

我试图创建预定义数量的行,每行都有预定义的字符数。允许的字符只有0和1,随机生成。基于VB.NET中的两个字符生成随机字符串

我已使用此代码来实现这一点:

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)。

任何人都可以帮我解决这个问题吗?

谢谢!

回答

0
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 
+0

感谢,作品像一个魅力! – globetrotter

+1

欢迎您,很高兴为您服务:-) – Zeddy