Compartir a través de


Random Clase

Definición

Representa un generador de números seudoaleatorios, que es un algoritmo que genera una secuencia de números que cumplen determinados requisitos estadísticos de aleatoriedad.

public ref class Random
public class Random
[System.Serializable]
public class Random
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class Random
type Random = class
[<System.Serializable>]
type Random = class
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type Random = class
Public Class Random
Herencia
Random
Atributos

Ejemplos

En el ejemplo siguiente se crea un único generador de números aleatorios y se llama a sus NextBytesmétodos , Nexty NextDouble para generar secuencias de números aleatorios dentro de intervalos diferentes.

using namespace System;

void main()
{
   // Instantiate random number generator using system-supplied value as seed.
   Random^ rand = gcnew Random();
   // Generate and display 5 random byte (integer) values.
   array<Byte>^ bytes = gcnew array<Byte>(4);
   rand->NextBytes(bytes);
   Console::WriteLine("Five random byte values:");
   for each (Byte byteValue in bytes)
      Console::Write("{0, 5}", byteValue);
   Console::WriteLine();
   // Generate and display 5 random integers.
   Console::WriteLine("Five random integer values:");
   for (int ctr = 0; ctr <= 4; ctr++)
      Console::Write("{0,15:N0}", rand->Next());
   Console::WriteLine();
   // Generate and display 5 random integers between 0 and 100.//
   Console::WriteLine("Five random integers between 0 and 100:");
   for (int ctr = 0; ctr <= 4; ctr++)
      Console::Write("{0,8:N0}", rand->Next(101));
   Console::WriteLine();
   // Generate and display 5 random integers from 50 to 100.
   Console::WriteLine("Five random integers between 50 and 100:");
   for (int ctr = 0; ctr <= 4; ctr++)
      Console::Write("{0,8:N0}", rand->Next(50, 101));
   Console::WriteLine();
   // Generate and display 5 random floating point values from 0 to 1.
   Console::WriteLine("Five Doubles.");
   for (int ctr = 0; ctr <= 4; ctr++)
      Console::Write("{0,8:N3}", rand->NextDouble());
   Console::WriteLine();
   // Generate and display 5 random floating point values from 0 to 5.
   Console::WriteLine("Five Doubles between 0 and 5.");
   for (int ctr = 0; ctr <= 4; ctr++)
      Console::Write("{0,8:N3}", rand->NextDouble() * 5);
}
// The example displays output like the following:
//    Five random byte values:
//      194  185  239   54  116
//    Five random integer values:
//        507,353,531  1,509,532,693  2,125,074,958  1,409,512,757    652,767,128
//    Five random integers between 0 and 100:
//          16      78      94      79      52
//    Five random integers between 50 and 100:
//          56      66      96      60      65
//    Five Doubles.
//       0.943   0.108   0.744   0.563   0.415
//    Five Doubles between 0 and 5.
//       2.934   3.130   0.292   1.432   4.369
// Instantiate random number generator using system-supplied value as seed.
var rand = new Random();

// Generate and display 5 random byte (integer) values.
byte[] bytes = new byte[5];
rand.NextBytes(bytes);
Console.WriteLine("Five random byte values:");
foreach (byte byteValue in bytes)
    Console.Write("{0, 5}", byteValue);
Console.WriteLine();

// Generate and display 5 random integers.
Console.WriteLine("Five random integer values:");
for (int ctr = 0; ctr <= 4; ctr++)
    Console.Write("{0,15:N0}", rand.Next());
Console.WriteLine();

// Generate and display 5 random integers between 0 and 100.
Console.WriteLine("Five random integers between 0 and 100:");
for (int ctr = 0; ctr <= 4; ctr++)
    Console.Write("{0,8:N0}", rand.Next(101));
Console.WriteLine();

// Generate and display 5 random integers from 50 to 100.
Console.WriteLine("Five random integers between 50 and 100:");
for (int ctr = 0; ctr <= 4; ctr++)
    Console.Write("{0,8:N0}", rand.Next(50, 101));
Console.WriteLine();

// Generate and display 5 random floating point values from 0 to 1.
Console.WriteLine("Five Doubles.");
for (int ctr = 0; ctr <= 4; ctr++)
    Console.Write("{0,8:N3}", rand.NextDouble());
Console.WriteLine();

// Generate and display 5 random floating point values from 0 to 5.
Console.WriteLine("Five Doubles between 0 and 5.");
for (int ctr = 0; ctr <= 4; ctr++)
    Console.Write("{0,8:N3}", rand.NextDouble() * 5);

// The example displays output like the following:
//    Five random byte values:
//      194  185  239   54  116
//    Five random integer values:
//        507,353,531  1,509,532,693  2,125,074,958  1,409,512,757    652,767,128
//    Five random integers between 0 and 100:
//          16      78      94      79      52
//    Five random integers between 50 and 100:
//          56      66      96      60      65
//    Five Doubles.
//       0.943   0.108   0.744   0.563   0.415
//    Five Doubles between 0 and 5.
//       2.934   3.130   0.292   1.432   4.369
// Instantiate random number generator using system-supplied value as seed.
let rand = Random()

// Generate and display 5 random byte (integer) values.
let bytes = Array.zeroCreate 5
rand.NextBytes bytes
printfn "Five random byte values:"
for byte in bytes do
    printf "%5i" byte
printfn ""

// Generate and display 5 random integers.
printfn "Five random integer values:"
for _ = 0 to 4 do
    printf $"{rand.Next(),15:N0}" 
printfn ""

// Generate and display 5 random integers between 0 and 100.
printfn "Five random integers between 0 and 100:"
for _ = 0 to 4 do
    printf $"{rand.Next 101,8:N0}"
printfn ""

// Generate and display 5 random integers from 50 to 100.
printfn "Five random integers between 50 and 100:"
for _ = 0 to 4 do
    printf $"{rand.Next(50, 101),8:N0}"
printfn ""

// Generate and display 5 random floating point values from 0 to 1.
printfn "Five Doubles."
for _ = 0 to 4 do
    printf $"{rand.NextDouble(),8:N3}"
printfn ""

// Generate and display 5 random floating point values from 0 to 5.
printfn "Five Doubles between 0 and 5."
for _ = 0 to 4 do
    printf $"{rand.NextDouble() * 5.0,8:N3}"

// The example displays output like the following:
//    Five random byte values:
//      194  185  239   54  116
//    Five random integer values:
//        507,353,531  1,509,532,693  2,125,074,958  1,409,512,757    652,767,128
//    Five random integers between 0 and 100:
//          16      78      94      79      52
//    Five random integers between 50 and 100:
//          56      66      96      60      65
//    Five Doubles.
//       0.943   0.108   0.744   0.563   0.415
//    Five Doubles between 0 and 5.
//       2.934   3.130   0.292   1.432   4.369
Module Example
   Public Sub Main()
      ' Instantiate random number generator using system-supplied value as seed.
      Dim rand As New Random()
      ' Generate and display 5 random byte (integer) values.
      Dim bytes(4) As Byte
      rand.NextBytes(bytes)
      Console.WriteLine("Five random byte values:")
      For Each byteValue As Byte In bytes
         Console.Write("{0, 5}", byteValue)
      Next
      Console.WriteLine()   
      ' Generate and display 5 random integers.
      Console.WriteLine("Five random integer values:")
      For ctr As Integer = 0 To 4
         Console.Write("{0,15:N0}", rand.Next)
      Next                     
      Console.WriteLine()
      ' Generate and display 5 random integers between 0 and 100.'
      Console.WriteLine("Five random integers between 0 and 100:")
      For ctr As Integer = 0 To 4
         Console.Write("{0,8:N0}", rand.Next(101))
      Next                     
      Console.WriteLine()
      ' Generate and display 5 random integers from 50 to 100.
      Console.WriteLine("Five random integers between 50 and 100:")
      For ctr As Integer = 0 To 4
         Console.Write("{0,8:N0}", rand.Next(50, 101))
      Next                     
      Console.WriteLine()
      ' Generate and display 5 random floating point values from 0 to 1.
      Console.WriteLine("Five Doubles.")
      For ctr As Integer = 0 To 4
         Console.Write("{0,8:N3}", rand.NextDouble())
      Next                     
      Console.WriteLine()
      ' Generate and display 5 random floating point values from 0 to 5.
      Console.WriteLine("Five Doubles between 0 and 5.")
      For ctr As Integer = 0 To 4
         Console.Write("{0,8:N3}", rand.NextDouble() * 5)
      Next                     
   End Sub
End Module
' The example displays output like the following:
'    Five random byte values:
'      194  185  239   54  116
'    Five random integer values:
'        507,353,531  1,509,532,693  2,125,074,958  1,409,512,757    652,767,128
'    Five random integers between 0 and 100:
'          16      78      94      79      52
'    Five random integers between 50 and 100:
'          56      66      96      60      65
'    Five Doubles.
'       0.943   0.108   0.744   0.563   0.415
'    Five Doubles between 0 and 5.
'       2.934   3.130   0.292   1.432   4.369

En el ejemplo siguiente se genera un entero aleatorio que usa como índice para recuperar un valor de cadena de una matriz.

using namespace System;

void main()
{
   Random^ rnd = gcnew Random();
   array<String^>^ malePetNames = { "Rufus", "Bear", "Dakota", "Fido",
                                    "Vanya", "Samuel", "Koani", "Volodya",
                                    "Prince", "Yiska" };
   array<String^>^ femalePetNames = { "Maggie", "Penny", "Saya", "Princess",
                                      "Abby", "Laila", "Sadie", "Olivia",
                                      "Starlight", "Talla" };
      
   // Generate random indexes for pet names.
   int mIndex = rnd->Next(malePetNames->Length);
   int fIndex = rnd->Next(femalePetNames->Length);
      
   // Display the result.
   Console::WriteLine("Suggested pet name of the day: ");
   Console::WriteLine("   For a male:     {0}", malePetNames[mIndex]);
   Console::WriteLine("   For a female:   {0}", femalePetNames[fIndex]);
}
// The example displays output similar to the following:
//       Suggested pet name of the day:
//          For a male:     Koani
//          For a female:   Maggie
Random rnd = new();
string[] malePetNames = [ "Rufus", "Bear", "Dakota", "Fido",
                        "Vanya", "Samuel", "Koani", "Volodya",
                        "Prince", "Yiska" ];
string[] femalePetNames = [ "Maggie", "Penny", "Saya", "Princess",
                          "Abby", "Laila", "Sadie", "Olivia",
                          "Starlight", "Talla" ];

// Generate random indexes for pet names.
int mIndex = rnd.Next(malePetNames.Length);
int fIndex = rnd.Next(femalePetNames.Length);

// Display the result.
Console.WriteLine("Suggested pet name of the day: ");
Console.WriteLine($"   For a male:     {malePetNames[mIndex]}");
Console.WriteLine($"   For a female:   {femalePetNames[fIndex]}");

// The example displays output similar to the following:
//       Suggested pet name of the day:
//          For a male:     Koani
//          For a female:   Maggie
let rnd = Random()

let malePetNames =
    [| "Rufus"; "Bear"; "Dakota"; "Fido";
        "Vanya"; "Samuel"; "Koani"; "Volodya";
        "Prince"; "Yiska" |]
let femalePetNames = 
    [| "Maggie"; "Penny"; "Saya"; "Princess";
        "Abby"; "Laila"; "Sadie"; "Olivia";
        "Starlight"; "Talla" |]

// Generate random indexes for pet names.
let mIndex = rnd.Next malePetNames.Length
let fIndex = rnd.Next femalePetNames.Length

// Display the result.
printfn "Suggested pet name of the day: "
printfn "   For a male:     %s" malePetNames.[mIndex]
printfn "   For a female:   %s" femalePetNames.[fIndex]

// The example displays output similar to the following:
//       Suggested pet name of the day:
//          For a male:     Koani
//          For a female:   Maggie
Module Example
   Public Sub Main()
      Dim rnd As New Random()
      Dim malePetNames() As String = { "Rufus", "Bear", "Dakota", "Fido", 
                                    "Vanya", "Samuel", "Koani", "Volodya", 
                                    "Prince", "Yiska" }
      Dim femalePetNames() As String = { "Maggie", "Penny", "Saya", "Princess", 
                                         "Abby", "Laila", "Sadie", "Olivia", 
                                         "Starlight", "Talla" }                                      
      
      ' Generate random indexes for pet names.
      Dim mIndex As Integer = rnd.Next(malePetNames.Length)
      Dim fIndex As Integer = rnd.Next(femalePetNames.Length)
      
      ' Display the result.
      Console.WriteLine("Suggested pet name of the day: ")
      Console.WriteLine("   For a male:     {0}", malePetNames(mIndex))
      Console.WriteLine("   For a female:   {0}", femalePetNames(fIndex))
   End Sub
End Module
' The example displays output similar to the following:
'       Suggested pet name of the day:
'          For a male:     Koani
'          For a female:   Maggie

Comentarios

Para obtener más información sobre esta API, consulte Comentarios complementarios de la API para Random.

Notas a los desarrolladores de herederos

En .NET Framework 2.0 y versiones posteriores, el comportamiento de los Next()métodos , Next(Int32, Int32)y NextBytes(Byte[]) ha cambiado para que estos métodos no llamen necesariamente a la implementación de clase derivada del Sample() método . Como resultado, las clases derivadas de Random ese destino de .NET Framework 2.0 y versiones posteriores también deben invalidar estos tres métodos.

Notas a los autores de las llamadas

No se garantiza que la implementación del generador de números aleatorios de la Random clase siga siendo la misma en las versiones principales de .NET. Como resultado, no debe suponer que la misma inicialización dará lugar a la misma secuencia pseudoaleatoriedad en diferentes versiones de .NET.

Constructores

Random()

Inicializa una nueva instancia de la clase Random mediante el uso de un valor de inicialización predeterminado.

Random(Int32)

Inicializa una nueva instancia de la clase Random utilizando el valor de inicialización especificado.

Propiedades

Shared

Proporciona una instancia segura Random para subprocesos que se puede usar simultáneamente desde cualquier subproceso.

Métodos

Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

(Heredado de Object)
GetHashCode()

Sirve como la función hash predeterminada.

(Heredado de Object)
GetItems<T>(ReadOnlySpan<T>, Int32)

Crea una matriz rellenada con elementos elegidos aleatoriamente a partir del conjunto de opciones proporcionado.

GetItems<T>(ReadOnlySpan<T>, Span<T>)

Rellena los elementos de un intervalo especificado con los elementos elegidos aleatoriamente del conjunto de opciones proporcionado.

GetItems<T>(T[], Int32)

Crea una matriz rellenada con elementos elegidos aleatoriamente a partir del conjunto de opciones proporcionado.

GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
Next()

Devuelve un entero aleatorio no negativo.

Next(Int32)

Devuelve un entero aleatorio no negativo que es inferior al máximo especificado.

Next(Int32, Int32)

Devuelve un entero aleatorio que está dentro de un intervalo especificado.

NextBytes(Byte[])

Rellena con números aleatorios los elementos de una matriz de bytes especificada.

NextBytes(Span<Byte>)

Rellena con números aleatorios los elementos de un intervalo de bytes especificado.

NextDouble()

Devuelve un número de punto flotante aleatorio que es mayor o igual que 0,0 y menor que 1,0.

NextInt64()

Devuelve un entero aleatorio no negativo.

NextInt64(Int64)

Devuelve un entero aleatorio no negativo que es inferior al máximo especificado.

NextInt64(Int64, Int64)

Devuelve un entero aleatorio que está dentro de un intervalo especificado.

NextSingle()

Devuelve un número de punto flotante aleatorio que es mayor o igual que 0,0 y menor que 1,0.

Sample()

Devuelve un número de punto flotante aleatorio entre 0,0 y 1,0.

Shuffle<T>(Span<T>)

Realiza un orden aleatorio en contexto de un intervalo.

Shuffle<T>(T[])

Realiza un orden aleatorio en contexto de una matriz.

ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Se aplica a