Ver Mensaje Individual
  #6 (permalink)  
Antiguo 07/09/2008, 10:57
dr--dre
 
Fecha de Ingreso: septiembre-2008
Mensajes: 4
Antigüedad: 16 años, 8 meses
Puntos: 0
Respuesta: Consulta sobre numeros aleatorios

Cita:
Iniciado por Avellaneda Ver Mensaje
Hola, prueba con esta función (la pongo bien comentada para que no tengas dudas):

Código:
Public Function Aleatorios(ByVal iNum As Integer, ByVal iInf As Integer, ByVal iSup As Integer) As Integer()
        Dim a() As Integer, i As Integer, j As Integer, x As Integer

        ReDim a(iNum - 1) ' redimensionamos la matriz (el subíndice es cero)
        Randomize()
        For i = 0 To iNum - 1
inicio:
            ' generamos un número aleatorio entre los valores indicados
            x = Int((iSup - iInf + 1) * Rnd + iInf)
            For j = 0 To i
                ' si el número ya existe en el array, lo descartamos
                If x = a(j) Then GoTo inicio
            Next j
            ' no existe, lo añadimos a la matriz
            a(i) = x
        Next i

        ' ordenamos el array (recuperamos las variables anteriores para no asignar nuevas)
        ' Nota: Si no los necesitas ordenados, suprime el siguiente bucle
        x = 1
        While (x = 1)
            x = 0
            For i = 1 To UBound(a)
                If a(i - 1) > a(i) Then
                    j = a(i - 1)
                    a(i - 1) = a(i)
                    a(i) = j
                    x = 1
                End If
            Next i
        End While
        ' devolvemos la matriz generada
        Return a
    End Function
Para llamarla, p.e. desde un Button:

Código:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ' parámetros: Cantidad de números, primer número, último número
        ' en este caso: 10 números alatorios sin repetición entre el 10 y el 30
        Dim miArray() As Integer = Aleatorios(10, 10, 30)

        ' los mostramos en un control ListBox (para comprobación)
        Dim i As Integer = 0
        ListBox1.Items.Clear()
        For i = 0 To UBound(miArray)
            ListBox1.Items.Add(miArray(i))
        Next i
    End Sub
muchas gracias, el codigo esta perfecto, es que precisamente lo necesitaba en ese tipo de estructura