none
Crear numeros aleatorios sin que se repitan (VB.NET) RRS feed

  • Pregunta

  • Estimados:

                     necesito generar números aleatorios en un textbox al presionar un boton pero sin que estos números se repitan...alguna idea de como puedo realizarlo.

    Muchas gracias.

    lunes, 20 de abril de 2015 15:45

Respuestas

  • Algo parecido a esta funcion

    Function RandomArray(min As Integer, max As Integer) As Integer()
    
        If min >= max Then
            Throw New Exception("Min. must be less than Max.)")
        End If
    
        Dim count As Integer = (max - min)
        Dim randomNumbers(count) As Integer
        Dim rand As New Random()
    
        ' Since an array of integers sets every number to zero, and zero is possibly within our min/max range (0-51 here),
        ' we have to initialize every number in the array to something that is outside our min/max range.
        If min <= 0 AndAlso max >= 0 Then
            For i As Integer = 0 To count
                randomNumbers(i) = (min - 1)    ' Could also be max + 1
            Next i
        End If
    
        Dim counter As Integer = 0
        ' Loop until the array has count # of elements (so counter will be equal to count + 1, since it is incremented AFTER we place a number in the array)
        Do Until counter = count + 1
            Dim someNumber As Integer = rand.Next(min, max + 1)
            ' Only add the number if it is not already in the array
            If Not randomNumbers.Contains(someNumber) Then
                randomNumbers(counter) = someNumber
                counter += 1
            End If
        Loop
    
        Return randomNumbers
    End Function

    lunes, 20 de abril de 2015 16:00