vendredi 5 février 2021

array of non-repeating random numbers in visual basic not working

I have the following code that receives a number and returns a random number between two ranges depending on the number passed by parameter.

Private Function GeneraNumero(ByVal columna)
        Dim value As Integer
        If columna = 0 Then
            value = CInt((1 - 9) * Rnd() + 9)

        ElseIf columna = 1 Then
            value = CInt((10 - 19) * Rnd() + 19)
        ElseIf columna = 2 Then
            value = CInt((20 - 29) * Rnd() + 29)
        ElseIf columna = 3 Then
            value = CInt((30 - 39) * Rnd() + 39)
        ElseIf columna = 4 Then
            value = CInt((40 - 49) * Rnd() + 49)
        ElseIf columna = 5 Then
            value = CInt((50 - 59) * Rnd() + 59)
        ElseIf columna = 6 Then
            value = CInt((60 - 69) * Rnd() + 69)
        ElseIf columna = 7 Then
            value = CInt((70 - 79) * Rnd() + 79)
        ElseIf columna = 8 Then
            value = CInt((80 - 90) * Rnd() + 90)
        End If
        Return value


    End Function

and this part is in charge of calling the previous code passing a different number as a parameter, after obtaining the random number I go through an array of numbers created to store them and if it is not found there then I save it if it is found I repeat the loop, then I create a button to which I assign that number as text and put the button in a TableLayoutPanel. So far so good, the only thing that happens is that there is always some repeated number and I am not able to see the failure, can someone help me? Thank you

Private Sub GenerarCarton()
        Dim repetido As Boolean = False
        filas = 3
        columnas = 9
        Dim numeros(27) As Integer
        Dim aleatorio As Integer
        Dim numero As Integer
        For i = 0 To filas - 1
            For j = 0 To columnas - 1
                Do
                    aleatorio = GeneraNumero(j)
                    For k = 0 To numeros.Length - 1
                        If numeros(k) <> aleatorio Then
                            numeros(k) = aleatorio
                            numero = aleatorio
                            repetido = True
                        Else
                            repetido = False
                        End If
                    Next
                Loop While repetido = True

                Dim miboton As New Button

                With miboton
                    .Name = "boton" & i & j
                    .Width = 50
                    .Height = 50
                    .Text = numero
                    .Top = .Height * ((i - 1) Mod filas) + 100
                    .Left = .Width * (j) + 10
                End With
                TableLayoutPanel1.Controls.Add(miboton)
                AddHandler miboton.MouseDown, AddressOf miclick
            Next j

        Next i

    End Sub

enter image description here




Aucun commentaire:

Enregistrer un commentaire