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

谁能帮我解决这个问题?

谢谢!

4

1 回答 1

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
于 2013-04-13T21:24:26.357 回答