2013-04-13 103 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