Random Random Random Random Class

定義

擬似乱数ジェネレーターを表します。擬似乱数ジェネレーターは、乱数についての統計的な要件を満たす数値系列を生成するデバイスです。Represents a pseudo-random number generator, which is a device that produces a sequence of numbers that meet certain statistical requirements for randomness.

public ref class Random
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class Random
type Random = class
Public Class Random
継承
RandomRandomRandomRandom
属性

次の例では、単一乱数ジェネレーターと呼び出しを作成します。 そのNextBytesNext、およびNextDoubleさまざまな範囲内のランダムな数値のシーケンスを生成するメソッド。The following example creates a single random number generator and calls its NextBytes, Next, and NextDouble methods to generate sequences of random numbers within different ranges.

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
using System;

public class Class1
{
   public static void Main()
   {
      // Instantiate random number generator using system-supplied value as seed.
      Random 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
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

次の例は、インデックスとして使用される整数の乱数を生成する、配列から文字列値を取得します。The following example generates a random integer that it uses as an index to retrieve a string value from an array.

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 the following output:
//       Suggested pet name of the day:
//          For a male:     Koani
//          For a female:   Maggie
using System;

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      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:     {0}", malePetNames[mIndex]);
      Console.WriteLine("   For a female:   {0}", femalePetNames[fIndex]);
   }
}
// The example displays the following output:
//       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 like the following:
'       Suggested pet name of the day:
'          For a male:     Koani
'          For a female:   Maggie

注釈

数値の有限のセットから等しい確率で擬似乱数が選択されます。Pseudo-random numbers are chosen with equal probability from a finite set of numbers. 選択し、数学的アルゴリズムが使用されるが、実際には十分にランダムなために、選択した番号は完全にランダムではありません。The chosen numbers are not completely random because a mathematical algorithm is used to select them, but they are sufficiently random for practical purposes. 現在の実装、Randomクラスは E. Donald Knuth の減算乱数ジェネレーター アルゴリズムの変更版に基づいています。The current implementation of the Random class is based on a modified version of Donald E. Knuth's subtractive random number generator algorithm. 詳細については、D. E. を参照してください。For more information, see D. E. クヌースします。Knuth. コンピューターのプログラミングでは、ボリューム 2 のアート:Seminumerical アルゴリズムします。The Art of Computer Programming, Volume 2: Seminumerical Algorithms. Addison Wesley、読み取り、MA、3 番目のエディション、1997 です。Addison-Wesley, Reading, MA, third edition, 1997.

ランダムなパスワードを作成するのに適したものなどの暗号強度が高いランダムな数値を生成するには使用、RNGCryptoServiceProviderクラスまたは派生クラスをSystem.Security.Cryptography.RandomNumberGeneratorします。To generate a cryptographically secure random number, such as one that's suitable for creating a random password, use the RNGCryptoServiceProvider class or derive a class from System.Security.Cryptography.RandomNumberGenerator.

このトピックの内容:In this topic:

乱数ジェネレーターをインスタンス化します。 Instantiating the random number generator
複数のインスタンス化を回避します。 Avoiding multiple instantiations
System.Random クラスおよびスレッドの安全性 The System.Random class and thread safety
さまざまな種類の乱数を生成します。 Generating different types of random numbers
独自のアルゴリズムの置換 Substituting your own algorithm
System.Random を使用するには. How do you use System.Random to…
ランダムな値の同じシーケンスを取得します。Retrieve the same sequence of random values
ランダムな値の一意のシーケンスを取得します。Retrieve unique sequences of random values
指定した範囲の整数を取得します。Retrieve integers in a specified range
指定した桁数を持つ整数を取得します。Retrieve integers with a specified number of digits
指定した範囲の浮動小数点値を取得します。Retrieve floating-point values in a specified range
ランダムなブール値を生成します。Generate random Boolean values
64 ビットの整数の乱数を生成します。Generate random 64-bit integers
指定した範囲内のバイトを取得します。Retrieve bytes in a specified range
配列またはコレクションから要素をランダムに取得します。Retrieve an element from an array or collection at random
配列またはコレクションからの一意の要素を取得します。Retrieve a unique element from an array or collection

乱数ジェネレーターをインスタンス化します。Instantiating the random number generator

シード値 (擬似乱数生成アルゴリズムの開始値) を提供することで、乱数ジェネレーターをインスタンス化する、Randomクラスのコンス トラクター。You instantiate the random number generator by providing a seed value (a starting value for the pseudo-random number generation algorithm) to a Random class constructor. 明示的または暗黙的にシード値を指定できます。You can supply the seed value either explicitly or implicitly:

  • Random(Int32)コンス トラクターは指定する明示的なシード値を使用します。The Random(Int32) constructor uses an explicit seed value that you supply.

  • Random()コンス トラクターでは、システム クロックを使用して、シード値を提供します。The Random() constructor uses the system clock to provide a seed value. これは、乱数ジェネレーターをインスタンス化する最も一般的な方法です。This is the most common way of instantiating the random number generator.

同じシードが個別に使用される場合Randomオブジェクト、同じ一連のランダムな番号が生成されます。If the same seed is used for separate Random objects, they will generate the same series of random numbers. 乱数値を処理するテスト スイートを作成するため、またはそのデータをランダムな数値から派生したゲームを再生するために役立ちます。 ことができます。This can be useful for creating a test suite that processes random values, or for replaying games that derive their data from random numbers. ただし、Random同一のシード値がインスタンス化している場合でも、異なるバージョンの .NET Framework で実行されているプロセス内のオブジェクトが別の一連のランダムな数値を返す可能性があります。However, note that Random objects in processes running under different versions of the .NET Framework may return different series of random numbers even if they're instantiated with identical seed values.

ランダムな数値のさまざまなシーケンスを生成するために行うことができます、シード値時間に依存のための新しいインスタンスごとに別の系列を生成Randomします。To produce different sequences of random numbers, you can make the seed value time-dependent, thereby producing a different series with each new instance of Random. パラメーター化されたRandom(Int32)コンス トラクターがかかることができます、Int32値に基づいてタイマー刻みの数、現在の時刻では、パラメーターなしRandom()コンス トラクターでは、システム クロックを使用して、シード値を生成します。The parameterized Random(Int32) constructor can take an Int32 value based on the number of ticks in the current time, whereas the parameterless Random() constructor uses the system clock to generate its seed value. ただし、クロックは有限の解像度があるために、このパラメーターなしのコンス トラクターを異なるを作成する使用Random連続でオブジェクトが同一のシーケンスのランダムな数値を生成する乱数ジェネレーターを作成します。However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers. 次の例 2 つRandom連続でインスタンス化されるオブジェクトは、同一の一連のランダムな数値を生成します。The following example illustrates how two Random objects that are instantiated in close succession generate an identical series of random numbers. ほとんどの Windows システムでRandom互いの 15 ミリ秒以内に作成されたオブジェクトが同一のシード値を持つ可能性があります。On most Windows systems, Random objects created within 15 milliseconds of one another are likely to have identical seed values.

using namespace System;

void main()
{
   array<Byte>^ bytes1 = gcnew array<Byte>(100);
   array<Byte>^ bytes2 = gcnew array<Byte>(100);
   Random^ rnd1 = gcnew Random();
   Random^ rnd2 = gcnew Random();
   
   rnd1->NextBytes(bytes1);
   rnd2->NextBytes(bytes2);
   
   Console::WriteLine("First Series:");
   for (int ctr = bytes1->GetLowerBound(0);
        ctr <= bytes1->GetUpperBound(0);
        ctr++) { 
      Console::Write("{0, 5}", bytes1[ctr]);
      if ((ctr + 1) % 10 == 0) Console::WriteLine();
   } 
   Console::WriteLine();
   Console::WriteLine("Second Series:");
   for (int ctr = bytes2->GetLowerBound(0);
        ctr <= bytes2->GetUpperBound(0);
        ctr++) {
      Console::Write("{0, 5}", bytes2[ctr]);
      if ((ctr + 1) % 10 == 0) Console::WriteLine();
   }   
}
// The example displays output like the following:
//       First Series:
//          97  129  149   54   22  208  120  105   68  177
//         113  214   30  172   74  218  116  230   89   18
//          12  112  130  105  116  180  190  200  187  120
//           7  198  233  158   58   51   50  170   98   23
//          21    1  113   74  146  245   34  255   96   24
//         232  255   23    9  167  240  255   44  194   98
//          18  175  173  204  169  171  236  127  114   23
//         167  202  132   65  253   11  254   56  214  127
//         145  191  104  163  143    7  174  224  247   73
//          52    6  231  255    5  101   83  165  160  231
//       
//       Second Series:
//          97  129  149   54   22  208  120  105   68  177
//         113  214   30  172   74  218  116  230   89   18
//          12  112  130  105  116  180  190  200  187  120
//           7  198  233  158   58   51   50  170   98   23
//          21    1  113   74  146  245   34  255   96   24
//         232  255   23    9  167  240  255   44  194   98
//          18  175  173  204  169  171  236  127  114   23
//         167  202  132   65  253   11  254   56  214  127
//         145  191  104  163  143    7  174  224  247   73
//          52    6  231  255    5  101   83  165  160  231        
using System;

public class Class1
{
   public static void Main()
   {
      byte[] bytes1 = new byte[100];
      byte[] bytes2 = new byte[100];
      Random rnd1 = new Random();
      Random rnd2 = new Random();
      
      rnd1.NextBytes(bytes1);
      rnd2.NextBytes(bytes2);
      
      Console.WriteLine("First Series:");
      for (int ctr = bytes1.GetLowerBound(0); 
           ctr <= bytes1.GetUpperBound(0); 
           ctr++) { 
         Console.Write("{0, 5}", bytes1[ctr]);
         if ((ctr + 1) % 10 == 0) Console.WriteLine();
      } 
      Console.WriteLine();
      Console.WriteLine("Second Series:");        
      for (int ctr = bytes2.GetLowerBound(0);
           ctr <= bytes2.GetUpperBound(0);
           ctr++) {
         Console.Write("{0, 5}", bytes2[ctr]);
         if ((ctr + 1) % 10 == 0) Console.WriteLine();
      }   
   }
}
// The example displays output like the following:
//       First Series:
//          97  129  149   54   22  208  120  105   68  177
//         113  214   30  172   74  218  116  230   89   18
//          12  112  130  105  116  180  190  200  187  120
//           7  198  233  158   58   51   50  170   98   23
//          21    1  113   74  146  245   34  255   96   24
//         232  255   23    9  167  240  255   44  194   98
//          18  175  173  204  169  171  236  127  114   23
//         167  202  132   65  253   11  254   56  214  127
//         145  191  104  163  143    7  174  224  247   73
//          52    6  231  255    5  101   83  165  160  231
//       
//       Second Series:
//          97  129  149   54   22  208  120  105   68  177
//         113  214   30  172   74  218  116  230   89   18
//          12  112  130  105  116  180  190  200  187  120
//           7  198  233  158   58   51   50  170   98   23
//          21    1  113   74  146  245   34  255   96   24
//         232  255   23    9  167  240  255   44  194   98
//          18  175  173  204  169  171  236  127  114   23
//         167  202  132   65  253   11  254   56  214  127
//         145  191  104  163  143    7  174  224  247   73
//          52    6  231  255    5  101   83  165  160  231        
Module modMain

   Public Sub Main()
      Dim bytes1(99), bytes2(99) As Byte
      Dim rnd1 As New Random()
      Dim rnd2 As New Random()
      
      rnd1.NextBytes(bytes1)
      rnd2.NextBytes(bytes2)
      
      Console.WriteLine("First Series:")
      For ctr As Integer = bytes1.GetLowerBound(0) to bytes1.GetUpperBound(0)
         Console.Write("{0, 5}", bytes1(ctr))
         If (ctr + 1) Mod 10 = 0 Then Console.WriteLine()
      Next 
      Console.WriteLine()
      Console.WriteLine("Second Series:")        
      For ctr As Integer = bytes2.GetLowerBound(0) to bytes2.GetUpperBound(0)
         Console.Write("{0, 5}", bytes2(ctr))
         If (ctr + 1) Mod 10 = 0 Then Console.WriteLine()
      Next   
   End Sub
End Module
' The example displays output like the following:
'       First Series:
'          97  129  149   54   22  208  120  105   68  177
'         113  214   30  172   74  218  116  230   89   18
'          12  112  130  105  116  180  190  200  187  120
'           7  198  233  158   58   51   50  170   98   23
'          21    1  113   74  146  245   34  255   96   24
'         232  255   23    9  167  240  255   44  194   98
'          18  175  173  204  169  171  236  127  114   23
'         167  202  132   65  253   11  254   56  214  127
'         145  191  104  163  143    7  174  224  247   73
'          52    6  231  255    5  101   83  165  160  231
'       
'       Second Series:
'          97  129  149   54   22  208  120  105   68  177
'         113  214   30  172   74  218  116  230   89   18
'          12  112  130  105  116  180  190  200  187  120
'           7  198  233  158   58   51   50  170   98   23
'          21    1  113   74  146  245   34  255   96   24
'         232  255   23    9  167  240  255   44  194   98
'          18  175  173  204  169  171  236  127  114   23
'         167  202  132   65  253   11  254   56  214  127
'         145  191  104  163  143    7  174  224  247   73
'          52    6  231  255    5  101   83  165  160  231      

この問題を回避するには、1 つを作成Random複数のオブジェクトではなくオブジェクト。To avoid this problem, create a single Random object instead of multiple objects.

複数のインスタンス化を回避します。Avoiding multiple instantiations

2 つの random number generator または立て続けに短いループ内の初期化中には、ランダムな数値の同一のシーケンスを生成できる 2 つの random number generator が作成されます。Initializing two random number generators in a tight loop or in rapid succession creates two random number generators that can produce identical sequences of random numbers. ほとんどの場合、これは、開発者の意図でありをインスタンス化し、乱数ジェネレーターの初期化がプロセスが比較的安価であるため、パフォーマンスの問題につながることができます。In most cases, this is not the developer's intent and can lead to performance issues, because instantiating and initializing a random number generator is a relatively expensive process.

両方のパフォーマンスを向上させるために、誤って同じ数値のシーケンスを生成する別の random number generator を作成しないようにする、1 つを作成すること勧めRandomオブジェクトを作成する代わりに、時間の経過と共に多くの乱数を生成するには新しいRandom1 つの乱数を生成するオブジェクト。Both to improve performance and to avoid inadvertently creating separate random number generators that generate identical numeric sequences, we recommend that you create one Random object to generate many random numbers over time, instead of creating new Random objects to generate one random number.

ただし、Randomクラスは、スレッド セーフであります。However, the Random class isn't thread safe. 呼び出す場合Random、複数のスレッドからメソッドが次のセクションで説明されているガイドラインに従います。If you call Random methods from multiple threads, follow the guidelines discussed in the next section.

System.Random クラスおよびスレッドの安全性The System.Random class and thread safety

個々 のインスタンス化するのではなくRandomオブジェクト、1 つを作成することをお勧めします。Randomインスタンスにより、アプリが必要なすべての乱数を生成します。Instead of instantiating individual Random objects, we recommend that you create a single Random instance to generate all the random numbers needed by your app. ただし、Randomオブジェクトはスレッド セーフではありません。However, Random objects are not thread safe. アプリを呼び出す場合Random複数のスレッドからメソッド、1 つのスレッドが一度に乱数ジェネレーターをアクセスできるようにする同期オブジェクトを使用する必要があります。If your app calls Random methods from multiple threads, you must use a synchronization object to ensure that only one thread can access the random number generator at a time. いることを確認しない場合、Randomオブジェクトがスレッド セーフな方法でアクセスされる、ランダムな数値を返すメソッドを呼び出すには 0 が返されます。If you don't ensure that the Random object is accessed in a thread-safe way, calls to methods that return random numbers return 0.

次の例では、c# 使用lock ステートメントおよび Visual Basic SyncLock ステートメントを 1 つ乱数ジェネレーターにスレッド セーフ方式で 11 のスレッドによってアクセスすることを確認します。The following example uses the C# lock Statement and the Visual Basic SyncLock statement to ensure that a single random number generator is accessed by 11 threads in a thread-safe manner. 各スレッドで 200万の乱数を生成し生成されたランダムな数字の数をカウント、その合計を計算し、実行が完了すると、すべてのスレッドの合計を更新します。Each thread generates 2 million random numbers, counts the number of random numbers generated and calculates their sum, and then updates the totals for all threads when it finishes executing.

using namespace System;
using namespace System::Threading;

ref class Example
{
private:
   [ThreadStatic] static double previous = 0.0;
   [ThreadStatic] static int perThreadCtr = 0;
   [ThreadStatic] static double perThreadTotal = 0.0;  
   static CancellationTokenSource^ source;
   static CountdownEvent^ countdown;
   static Object^ randLock;
   static Object^ numericLock;
   static Random^ rand;
   double totalValue = 0.0;
   int totalCount = 0;
   
public:
   Example()
   { 
      rand = gcnew Random();
      randLock = gcnew Object();
      numericLock = gcnew Object();
      countdown = gcnew CountdownEvent(1);
      source = gcnew CancellationTokenSource();
   } 

   void Execute()
   {   
      CancellationToken^ token = source->Token;

      for (int threads = 1; threads <= 10; threads++)
      {
         Thread^ newThread = gcnew Thread(gcnew ParameterizedThreadStart(this, &Example::GetRandomNumbers));
         newThread->Name = threads.ToString();
         newThread->Start(token);
      }
      this->GetRandomNumbers(token);
      
      countdown->Signal();
      // Make sure all threads have finished.
      countdown->Wait();

      Console::WriteLine("\nTotal random numbers generated: {0:N0}", totalCount);
      Console::WriteLine("Total sum of all random numbers: {0:N2}", totalValue);
      Console::WriteLine("Random number mean: {0:N4}", totalValue/totalCount);
   }

private:
   void GetRandomNumbers(Object^ o)
   {
      CancellationToken^ token = (CancellationToken) o;
      double result = 0.0;
      countdown->AddCount(1);
         
      try { 
         for (int ctr = 0; ctr < 2000000; ctr++)
         {
            // Make sure there's no corruption of Random.
            token->ThrowIfCancellationRequested();

            Monitor::Enter(randLock);
            result = rand->NextDouble();
            Monitor::Exit(randLock);
            // Check for corruption of Random instance.
            if ((result == previous) && result == 0) {
               source->Cancel();
            }
            else {
               previous = result;
            }
            perThreadCtr++;
            perThreadTotal += result;
         }      
       
         Console::WriteLine("Thread {0} finished execution.", 
                           Thread::CurrentThread->Name);
         Console::WriteLine("Random numbers generated: {0:N0}", perThreadCtr);
         Console::WriteLine("Sum of random numbers: {0:N2}", perThreadTotal);
         Console::WriteLine("Random number mean: {0:N4}\n", perThreadTotal/perThreadCtr);

         // Update overall totals.
         Monitor::Enter(numericLock);
         totalCount += perThreadCtr;
         totalValue += perThreadTotal;  
         Monitor::Exit(numericLock);
      }
      catch (OperationCanceledException^ e) {
         Console::WriteLine("Corruption in Thread {1}", e->GetType()->Name,
                            Thread::CurrentThread->Name);
      }
      finally {
         countdown->Signal();
      }
   }
};

void main()
{
   Example^ ex = gcnew Example();
   Thread::CurrentThread->Name = "Main";
   ex->Execute();
}
// The example displays output like the following:
//       Thread 6 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 1,000,491.05
//       Random number mean: 0.5002
//       
//       Thread 10 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 999,329.64
//       Random number mean: 0.4997
//       
//       Thread 4 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 1,000,166.89
//       Random number mean: 0.5001
//       
//       Thread 8 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 999,628.37
//       Random number mean: 0.4998
//       
//       Thread Main finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 999,920.89
//       Random number mean: 0.5000
//       
//       Thread 3 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 999,370.45
//       Random number mean: 0.4997
//       
//       Thread 7 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 999,330.92
//       Random number mean: 0.4997
//       
//       Thread 9 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 1,000,172.79
//       Random number mean: 0.5001
//       
//       Thread 5 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 1,000,079.43
//       Random number mean: 0.5000
//       
//       Thread 1 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 999,817.91
//       Random number mean: 0.4999
//       
//       Thread 2 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 999,930.63
//       Random number mean: 0.5000
//       
//       
//       Total random numbers generated: 22,000,000
//       Total sum of all random numbers: 10,998,238.98
//       Random number mean: 0.4999
using System;
using System.Threading;

public class Example
{
   [ThreadStatic] static double previous = 0.0;
   [ThreadStatic] static int perThreadCtr = 0;
   [ThreadStatic] static double perThreadTotal = 0.0;  
   static CancellationTokenSource source;
   static CountdownEvent countdown; 
   static Object randLock, numericLock;
   static Random rand;
   double totalValue = 0.0;
   int totalCount = 0;
   
   public Example()
   { 
      rand = new Random();
      randLock = new Object();
      numericLock = new Object();
      countdown = new CountdownEvent(1);
      source = new CancellationTokenSource();
   } 

   public static void Main()
   {
      Example ex = new Example();
      Thread.CurrentThread.Name = "Main";
      ex.Execute();
   }

   private void Execute()
   {   
      CancellationToken token = source.Token; 

      for (int threads = 1; threads <= 10; threads++)
      {
         Thread newThread = new Thread(this.GetRandomNumbers);
         newThread.Name = threads.ToString();
         newThread.Start(token);
      }
      this.GetRandomNumbers(token);
      
      countdown.Signal();
      // Make sure all threads have finished.
      countdown.Wait();
      source.Dispose();

      Console.WriteLine("\nTotal random numbers generated: {0:N0}", totalCount);
      Console.WriteLine("Total sum of all random numbers: {0:N2}", totalValue);
      Console.WriteLine("Random number mean: {0:N4}", totalValue/totalCount);
   }

   private void GetRandomNumbers(Object o)
   {
      CancellationToken token = (CancellationToken) o;
      double result = 0.0;
      countdown.AddCount(1);
         
      try { 
         for (int ctr = 0; ctr < 2000000; ctr++)
         {
            // Make sure there's no corruption of Random.
            token.ThrowIfCancellationRequested();

            lock (randLock) {
               result = rand.NextDouble();
            }
            // Check for corruption of Random instance.
            if ((result == previous) && result == 0) {
               source.Cancel();
            }
            else {
               previous = result;
            }
            perThreadCtr++;
            perThreadTotal += result;
         }      
       
         Console.WriteLine("Thread {0} finished execution.", 
                           Thread.CurrentThread.Name);
         Console.WriteLine("Random numbers generated: {0:N0}", perThreadCtr);
         Console.WriteLine("Sum of random numbers: {0:N2}", perThreadTotal);
         Console.WriteLine("Random number mean: {0:N4}\n", perThreadTotal/perThreadCtr);

         // Update overall totals.
         lock (numericLock) {
            totalCount += perThreadCtr;
            totalValue += perThreadTotal;  
         }
      }
      catch (OperationCanceledException e) {
         Console.WriteLine("Corruption in Thread {1}", e.GetType().Name, Thread.CurrentThread.Name);
      }
      finally {
         countdown.Signal();        
      }
   }
}
// The example displays output like the following:
//       Thread 6 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 1,000,491.05
//       Random number mean: 0.5002
//       
//       Thread 10 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 999,329.64
//       Random number mean: 0.4997
//       
//       Thread 4 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 1,000,166.89
//       Random number mean: 0.5001
//       
//       Thread 8 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 999,628.37
//       Random number mean: 0.4998
//       
//       Thread Main finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 999,920.89
//       Random number mean: 0.5000
//       
//       Thread 3 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 999,370.45
//       Random number mean: 0.4997
//       
//       Thread 7 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 999,330.92
//       Random number mean: 0.4997
//       
//       Thread 9 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 1,000,172.79
//       Random number mean: 0.5001
//       
//       Thread 5 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 1,000,079.43
//       Random number mean: 0.5000
//       
//       Thread 1 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 999,817.91
//       Random number mean: 0.4999
//       
//       Thread 2 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 999,930.63
//       Random number mean: 0.5000
//       
//       
//       Total random numbers generated: 22,000,000
//       Total sum of all random numbers: 10,998,238.98
//       Random number mean: 0.4999
Imports System.Threading

Module Example
   <ThreadStatic> Dim previous As Double = 0.0
   <ThreadStatic> Dim perThreadCtr As Integer = 0
   <ThreadStatic> Dim perThreadTotal As Double = 0.0  
   Dim source As New CancellationTokenSource()
   Dim countdown As New CountdownEvent(1) 
   Dim randLock As New Object()
   Dim numericLock As New Object()
   Dim rand As New Random()
   Dim totalValue As Double = 0.0
   Dim totalCount As Integer = 0
   
   Public Sub Main()
      Thread.CurrentThread.Name = "Main"

      Dim token As CancellationToken = source.Token 
      For threads As Integer = 1 To 10
         Dim newThread As New Thread(AddressOf GetRandomNumbers)
         newThread.Name = threads.ToString()
         newThread.Start(token)
      Next
      GetRandomNumbers(token)
      
      countdown.Signal()
      ' Make sure all threads have finished.
      countdown.Wait()

      Console.WriteLine()
      Console.WriteLine("Total random numbers generated: {0:N0}", totalCount)
      Console.WriteLine("Total sum of all random numbers: {0:N2}", totalValue)
      Console.WriteLine("Random number mean: {0:N4}", totalValue/totalCount)
   End Sub

   Private Sub GetRandomNumbers(o As Object)
      Dim token As CancellationToken = CType(o, CancellationToken)
      Dim result As Double = 0.0
      countdown.AddCount(1)
         
      Try  
         For ctr As Integer = 1 To 2000000
            ' Make sure there's no corruption of Random.
            token.ThrowIfCancellationRequested()

            SyncLock randLock
               result = rand.NextDouble()
            End SyncLock
            ' Check for corruption of Random instance.
            If result = previous AndAlso result = 0 Then 
               source.Cancel()
            Else 
               previous = result
            End If
            perThreadCtr += 1
            perThreadTotal += result
         Next      
       
         Console.WriteLine("Thread {0} finished execution.", 
                           Thread.CurrentThread.Name)
         Console.WriteLine("Random numbers generated: {0:N0}", perThreadCtr)
         Console.WriteLine("Sum of random numbers: {0:N2}", perThreadTotal)
         Console.WriteLine("Random number mean: {0:N4}", perThreadTotal/perThreadCtr)
         Console.WriteLine()
         
         ' Update overall totals.
         SyncLock numericLock
            totalCount += perThreadCtr
            totalValue += perThreadTotal  
         End SyncLock
      Catch e As OperationCanceledException
         Console.WriteLine("Corruption in Thread {1}", e.GetType().Name, Thread.CurrentThread.Name)
      Finally 
         countdown.Signal()
         source.Dispose()
      End Try
   End Sub
End Module
' The example displays output like the following:
'       Thread 6 finished execution.
'       Random numbers generated: 2,000,000
'       Sum of random numbers: 1,000,491.05
'       Random number mean: 0.5002
'       
'       Thread 10 finished execution.
'       Random numbers generated: 2,000,000
'       Sum of random numbers: 999,329.64
'       Random number mean: 0.4997
'       
'       Thread 4 finished execution.
'       Random numbers generated: 2,000,000
'       Sum of random numbers: 1,000,166.89
'       Random number mean: 0.5001
'       
'       Thread 8 finished execution.
'       Random numbers generated: 2,000,000
'       Sum of random numbers: 999,628.37
'       Random number mean: 0.4998
'       
'       Thread Main finished execution.
'       Random numbers generated: 2,000,000
'       Sum of random numbers: 999,920.89
'       Random number mean: 0.5000
'       
'       Thread 3 finished execution.
'       Random numbers generated: 2,000,000
'       Sum of random numbers: 999,370.45
'       Random number mean: 0.4997
'       
'       Thread 7 finished execution.
'       Random numbers generated: 2,000,000
'       Sum of random numbers: 999,330.92
'       Random number mean: 0.4997
'       
'       Thread 9 finished execution.
'       Random numbers generated: 2,000,000
'       Sum of random numbers: 1,000,172.79
'       Random number mean: 0.5001
'       
'       Thread 5 finished execution.
'       Random numbers generated: 2,000,000
'       Sum of random numbers: 1,000,079.43
'       Random number mean: 0.5000
'       
'       Thread 1 finished execution.
'       Random numbers generated: 2,000,000
'       Sum of random numbers: 999,817.91
'       Random number mean: 0.4999
'       
'       Thread 2 finished execution.
'       Random numbers generated: 2,000,000
'       Sum of random numbers: 999,930.63
'       Random number mean: 0.5000
'       
'       
'       Total random numbers generated: 22,000,000
'       Total sum of all random numbers: 10,998,238.98
'       Random number mean: 0.4999

例では、次の方法でスレッド セーフを保証します。The example ensures thread-safety in the following ways:

  • ThreadStaticAttribute乱数を生成し、スレッドごとに、その合計の合計数を追跡するスレッド ローカル変数を定義する属性を使用します。The ThreadStaticAttribute attribute is used to define thread-local variables that track the total number of random numbers generated and their sum for each thread.

  • ロック (、 lock (C#) ステートメント、 SyncLock Visual Basic でのステートメント) の合計数とすべてのスレッドで生成されたすべてのランダムな数の合計、変数へのアクセスを保護します。A lock (the lock statement in C# and the SyncLock statement in Visual Basic) protects access to the variables for the total count and sum of all random numbers generated on all threads.

  • セマフォ (、CountdownEventオブジェクト)、メイン スレッドがブロックまで他のすべてのスレッドが実行を完了することを確認するために使用します。A semaphore (the CountdownEvent object) is used to ensure that the main thread blocks until all other threads complete execution.

  • この例では、かどうか、乱数ジェネレーターが破損を特定することにランダムな番号の生成方法の 2 つの連続した呼び出しは、0 を返すかどうかを確認します。The example checks whether the random number generator has become corrupted by determining whether two consecutive calls to random number generation methods return 0. 破損が検出された場合の例では、CancellationTokenSourceオブジェクトからすべてのスレッドを取り消す必要があることを通知します。If corruption is detected, the example uses the CancellationTokenSource object to signal that all threads should be canceled.

  • 状態を調べ、各スレッドごとの乱数を生成する前に、CancellationTokenオブジェクト。Before generating each random number, each thread checks the state of the CancellationToken object. キャンセルが要求される場合の例では、CancellationToken.ThrowIfCancellationRequestedスレッドをキャンセルするメソッド。If cancellation is requested, the example calls the CancellationToken.ThrowIfCancellationRequested method to cancel the thread.

使用する点を除いて、次の例は、最初と同じ、Taskオブジェクトとラムダ式の代わりにThreadオブジェクト。The following example is identical to the first, except that it uses a Task object and a lambda expression instead of Thread objects.

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   static Object randLock, numericLock;
   static Random rand;
   static CancellationTokenSource source;
   double totalValue = 0.0;
   int totalCount = 0;
   
   public Example()
   { 
      rand = new Random();
      randLock = new Object();
      numericLock = new Object();
      source = new CancellationTokenSource();
   } 

   public static async Task Main()
   {
      Example ex = new Example();
      Thread.CurrentThread.Name = "Main";
      await ex.Execute();
   }

   private Task Execute()
   {   
      List<Task> tasks = new List<Task>();
      
      for (int ctr = 0; ctr <= 10; ctr++)
      {
         CancellationToken token = source.Token; 
         int taskNo = ctr;
         tasks.Add(Task.Run( () =>
            {
               double previous = 0.0;
               int taskCtr = 0;
               double taskTotal = 0.0;  
               double result = 0.0;
                               
               for (int n = 0; n < 2000000; n++)
               {
                  // Make sure there's no corruption of Random.
                  token.ThrowIfCancellationRequested();

                  lock (randLock) {
                     result = rand.NextDouble();
                  }
                  // Check for corruption of Random instance.
                  if ((result == previous) && result == 0) {
                     source.Cancel();
                  }
                  else {
                     previous = result;
                  }
                  taskCtr++;
                  taskTotal += result;
               }

               // Show result.
               Console.WriteLine("Task {0} finished execution.", taskNo);
               Console.WriteLine("Random numbers generated: {0:N0}", taskCtr);
               Console.WriteLine("Sum of random numbers: {0:N2}", taskTotal);
               Console.WriteLine("Random number mean: {0:N4}\n", taskTotal/taskCtr);
         
               // Update overall totals.
               lock (numericLock) {
                  totalCount += taskCtr;
                  totalValue += taskTotal;  
               }
            }, 
         token));
      }
      try {
         await Task.WhenAll(tasks.ToArray());
         Console.WriteLine("\nTotal random numbers generated: {0:N0}", totalCount);
         Console.WriteLine("Total sum of all random numbers: {0:N2}", totalValue);
         Console.WriteLine("Random number mean: {0:N4}", totalValue/totalCount);
      }
      catch (AggregateException e) {
         foreach (Exception inner in e.InnerExceptions) {
            TaskCanceledException canc = inner as TaskCanceledException;
            if (canc != null)
               Console.WriteLine("Task #{0} cancelled.", canc.Task.Id);
            else
               Console.WriteLine("Exception: {0}", inner.GetType().Name);
         }         
      }
      finally {
         source.Dispose();
      }
   }
}
// The example displays output like the following:
//       Task 1 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 1,000,502.47
//       Random number mean: 0.5003
//       
//       Task 0 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 1,000,445.63
//       Random number mean: 0.5002
//       
//       Task 2 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 1,000,556.04
//       Random number mean: 0.5003
//       
//       Task 3 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 1,000,178.87
//       Random number mean: 0.5001
//       
//       Task 4 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 999,819.17
//       Random number mean: 0.4999
//       
//       Task 5 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 1,000,190.58
//       Random number mean: 0.5001
//       
//       Task 6 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 999,720.21
//       Random number mean: 0.4999
//       
//       Task 7 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 999,000.96
//       Random number mean: 0.4995
//       
//       Task 8 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 999,499.33
//       Random number mean: 0.4997
//       
//       Task 9 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 1,000,193.25
//       Random number mean: 0.5001
//       
//       Task 10 finished execution.
//       Random numbers generated: 2,000,000
//       Sum of random numbers: 999,960.82
//       Random number mean: 0.5000
//       
//       
//       Total random numbers generated: 22,000,000
//       Total sum of all random numbers: 11,000,067.33
//       Random number mean: 0.5000
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Dim source As New CancellationTokenSource()
   Dim randLock As New Object()
   Dim numericLock As New Object()
   Dim rand As New Random()
   Dim totalValue As Double = 0.0
   Dim totalCount As Integer = 0
   
   Public Sub Main()
      Dim tasks As New List(Of Task)()
      
      For ctr As Integer = 1 To 10
         Dim token As CancellationToken = source.Token 
         Dim taskNo As Integer = ctr
         tasks.Add(Task.Run( 
                   Sub()
                      Dim previous As Double = 0.0
                      Dim taskCtr As Integer = 0
                      Dim taskTotal As Double = 0.0
                      Dim result As Double = 0.0

                      For n As Integer = 1 To 2000000
                         ' Make sure there's no corruption of Random.
                         token.ThrowIfCancellationRequested()
      
                         SyncLock randLock
                           result = rand.NextDouble()
                         End SyncLock
                         ' Check for corruption of Random instance.
                         If result = previous AndAlso result = 0 Then
                           source.Cancel()
                         Else 
                           previous = result
                         End If
                        taskCtr += 1
                        taskTotal += result
                      Next   

                      ' Show result.
                     Console.WriteLine("Task {0} finished execution.", taskNo)
                     Console.WriteLine("Random numbers generated: {0:N0}", taskCtr)
                     Console.WriteLine("Sum of random numbers: {0:N2}", taskTotal)
                     Console.WriteLine("Random number mean: {0:N4}", taskTotal/taskCtr)
                     Console.WriteLine()
                     
                     ' Update overall totals.
                     SyncLock numericLock
                        totalCount += taskCtr
                        totalValue += taskTotal  
                     End SyncLock
                   End Sub, token))
      Next

      Try
         Task.WaitAll(tasks.ToArray())
         Console.WriteLine()
         Console.WriteLine("Total random numbers generated: {0:N0}", totalCount)
         Console.WriteLine("Total sum of all random numbers: {0:N2}", totalValue)
         Console.WriteLine("Random number mean: {0:N4}", totalValue/totalCount)
      Catch e As AggregateException
         For Each inner As Exception In e.InnerExceptions
            Dim canc As TaskCanceledException = TryCast(inner, TaskCanceledException)
            If canc IsNot Nothing Then
               Console.WriteLine("Task #{0} cancelled.", canc.Task.Id)
            Else
               Console.WriteLine("Exception: {0}", inner.GetType().Name)
            End If   
         Next         
      Finally
         source.Dispose()
      End Try
   End Sub
End Module
' The example displays output like the following:
'       Task 1 finished execution.
'       Random numbers generated: 2,000,000
'       Sum of random numbers: 1,000,502.47
'       Random number mean: 0.5003
'       
'       Task 0 finished execution.
'       Random numbers generated: 2,000,000
'       Sum of random numbers: 1,000,445.63
'       Random number mean: 0.5002
'       
'       Task 2 finished execution.
'       Random numbers generated: 2,000,000
'       Sum of random numbers: 1,000,556.04
'       Random number mean: 0.5003
'       
'       Task 3 finished execution.
'       Random numbers generated: 2,000,000
'       Sum of random numbers: 1,000,178.87
'       Random number mean: 0.5001
'       
'       Task 4 finished execution.
'       Random numbers generated: 2,000,000
'       Sum of random numbers: 999,819.17
'       Random number mean: 0.4999
'       
'       Task 5 finished execution.
'       Random numbers generated: 2,000,000
'       Sum of random numbers: 1,000,190.58
'       Random number mean: 0.5001
'       
'       Task 6 finished execution.
'       Random numbers generated: 2,000,000
'       Sum of random numbers: 999,720.21
'       Random number mean: 0.4999
'       
'       Task 7 finished execution.
'       Random numbers generated: 2,000,000
'       Sum of random numbers: 999,000.96
'       Random number mean: 0.4995
'       
'       Task 8 finished execution.
'       Random numbers generated: 2,000,000
'       Sum of random numbers: 999,499.33
'       Random number mean: 0.4997
'       
'       Task 9 finished execution.
'       Random numbers generated: 2,000,000
'       Sum of random numbers: 1,000,193.25
'       Random number mean: 0.5001
'       
'       Task 10 finished execution.
'       Random numbers generated: 2,000,000
'       Sum of random numbers: 999,960.82
'       Random number mean: 0.5000
'       
'       
'       Total random numbers generated: 22,000,000
'       Total sum of all random numbers: 11,000,067.33
'       Random number mean: 0.5000

最初の例から次の方法で異なります。It differs from the first example in the following ways:

  • 使用する必要はありませんので、生成されたランダムな数字の数と各タスクでは、その合計を追跡する変数はタスクは、ローカル、ThreadStaticAttribute属性。The variables to keep track of the number of random numbers generated and their sum in each task are local to the task, so there is no need to use the ThreadStaticAttribute attribute.

  • 静的なTask.WaitAllメソッドを使用して、すべてのタスクが完了する前に、メイン スレッドが完了しないことを確認します。The static Task.WaitAll method is used to ensure that the main thread doesn't complete before all tasks have finished. 必要はありません、CountdownEventオブジェクト。There is no need for the CountdownEvent object.

  • タスクのキャンセルに起因する例外が表示される、Task.WaitAllメソッド。The exception that results from task cancellation is surfaced in the Task.WaitAll method. 前の例では、各スレッドで処理されます。In the previous example, it is handled by each thread.

さまざまな種類の乱数を生成します。Generating different types of random numbers

乱数ジェネレーターは、次の種類の乱数を生成できるメソッドを提供します。The random number generator provides methods that let you generate the following kinds of random numbers:

  • 一連のByte値。A series of Byte values. メソッドに戻るようにする要素の数に初期化された配列を渡すことによってバイト値の数を決定する、NextBytesメソッド。You determine the number of byte values by passing an array initialized to the number of elements you want the method to return to the NextBytes method. 次の例では、20 バイトを生成します。The following example generates 20 bytes.

    using namespace System;
    
    void main()
    {
       Random^ rnd = gcnew Random();
       array<Byte>^ bytes = gcnew array<Byte>(20);
       rnd->NextBytes(bytes);
       for (int ctr = 1; ctr <= bytes->Length; ctr++) {
          Console::Write("{0,3}   ", bytes[ctr - 1]);
          if (ctr % 10 == 0) Console::WriteLine();
       } 
    }
    // The example displays output like the following:
    //       141    48   189    66   134   212   211    71   161    56
    //       181   166   220   133     9   252   222    57    62    62
    
    using System;
    
    public class Example
    {
       public static void Main()
       {
          Random rnd = new Random();
          Byte[] bytes = new Byte[20];
          rnd.NextBytes(bytes);  
          for (int ctr = 1; ctr <= bytes.Length; ctr++) {
             Console.Write("{0,3}   ", bytes[ctr - 1]);
             if (ctr % 10 == 0) Console.WriteLine();
          } 
       }
    }
    // The example displays output like the following:
    //       141    48   189    66   134   212   211    71   161    56
    //       181   166   220   133     9   252   222    57    62    62
    
    Module Example
       Public Sub Main()
          Dim rnd As New Random()
          Dim bytes(19) As Byte
          rnd.NextBytes(bytes)  
          For ctr As Integer = 1 To bytes.Length
             Console.Write("{0,3}   ", bytes(ctr - 1))
             If ctr Mod 10 = 0 Then Console.WriteLine()
          Next 
       End Sub
    End Module
    ' The example displays output like the following:
    '       141    48   189    66   134   212   211    71   161    56
    '       181   166   220   133     9   252   222    57    62    62
    
  • 1 つの整数。A single integer. 最大値は 0 から整数にするかどうかを選択できます (Int32.MaxValue - 1) を呼び出して、Next()メソッドは、0 から呼び出すことによって、特定の値までの整数、Next(Int32)メソッド、または、を呼び出すことによって値の範囲内の整数Next(Int32, Int32)メソッド。You can choose whether you want an integer from 0 to a maximum value (Int32.MaxValue - 1) by calling the Next() method, an integer between 0 and a specific value by calling the Next(Int32) method, or an integer within a range of values by calling the Next(Int32, Int32) method. パラメーター化されたオーバー ロードで指定された最大値は排他的です。生成された実際の最大数は、1 つは、指定した値より小さくします。In the parameterized overloads, the specified maximum value is exclusive; that is, the actual maximum number generated is one less than the specified value.

    次の例では、 Next(Int32, Int32) -10 ~ 10 の間の 10 個の乱数を生成します。The following example calls the Next(Int32, Int32) method to generate 10 random numbers between -10 and 10. メソッドの 2 番目の引数がメソッドによって返されるランダムな値の範囲の上限を指定することに注意してください。Note that the second argument to the method specifies the exclusive upper bound of the range of random values returned by the method. つまり、メソッドは、1 つを返すことができる最大の整数値よりも小さい値です。In other words, the largest integer that the method can return is one less than this value.

    using namespace System;
    
    void main()
    {
       Random^ rnd = gcnew Random();
       for (int ctr = 0; ctr < 10; ctr++) {
          Console::Write("{0,3}   ", rnd->Next(-10, 11));
       }
    }
    // The example displays output like the following:
    //    2     9    -3     2     4    -7    -3    -8    -8     5
    
    using System;
    
    public class Example
    {
       public static void Main()
       {
          Random rnd = new Random();
          for (int ctr = 0; ctr < 10; ctr++) {
             Console.Write("{0,3}   ", rnd.Next(-10, 11));
          }
       }
    }
    // The example displays output like the following:
    //    2     9    -3     2     4    -7    -3    -8    -8     5
    
    Module Example
       Public Sub Main()
          Dim rnd As New Random()
          For ctr As Integer = 0 To 9
             Console.Write("{0,3}   ", rnd.Next(-10, 11))
          Next
       End Sub
    End Module
    ' The example displays output like the following:
    '    2     9    -3     2     4    -7    -3    -8    -8     5
    
  • 呼び出すことによって 1.0 より小さい 0.0 から 1 つの浮動小数点値、NextDoubleメソッド。A single floating-point value from 0.0 to less than 1.0 by calling the NextDouble method. メソッドによって返される乱数の排他的上限値は、その実際の上限は 0.99999999999999978 1 です。The exclusive upper bound of the random number returned by the method is 1, so its actual upper bound is 0.99999999999999978. 次の例では、10 個のランダムな浮動小数点数値を生成します。The following example generates 10 random floating-point numbers.

    using namespace System;
    
    void main()
    {
       Random^ rnd = gcnew Random();
       for (int ctr = 0; ctr < 10; ctr++) {
          Console::Write("{0,-19:R}   ", rnd->NextDouble());
          if ((ctr + 1) % 3 == 0) Console::WriteLine();
       }
    }
    // The example displays output like the following:
    //    0.7911680553998649    0.0903414949264105    0.79776258291572455    
    //    0.615568345233597     0.652644504165577     0.84023809378977776   
    //    0.099662564741290441   0.91341467383942321  0.96018602045261581   
    //    0.74772306473354022
    
    using System;
    
    public class Example
    {
       public static void Main()
       {
          Random rnd = new Random();
          for (int ctr = 0; ctr < 10; ctr++) {
             Console.Write("{0,-19:R}   ", rnd.NextDouble());
             if ((ctr + 1) % 3 == 0) Console.WriteLine();
          }
       }
    }
    // The example displays output like the following:
    //    0.7911680553998649    0.0903414949264105    0.79776258291572455    
    //    0.615568345233597     0.652644504165577     0.84023809378977776   
    //    0.099662564741290441   0.91341467383942321  0.96018602045261581   
    //    0.74772306473354022
    
    Module Example
       Public Sub Main()
          Dim rnd As New Random()
          For ctr As Integer = 0 To 9
             Console.Write("{0,-19:R}   ", rnd.NextDouble())
             If (ctr + 1) Mod 3 = 0 Then Console.WriteLine()
          Next
       End Sub
    End Module
    ' The example displays output like the following:
    '    0.7911680553998649    0.0903414949264105    0.79776258291572455    
    '    0.615568345233597     0.652644504165577     0.84023809378977776   
    '    0.099662564741290441  0.91341467383942321   0.96018602045261581   
    '    0.74772306473354022
    

重要

Next(Int32, Int32)メソッドでは、返される乱数の範囲を指定できます。The Next(Int32, Int32) method allows you to specify the range of the returned random number. ただし、maxValue範囲の上限に返される数値を指定するには、パラメーターは、排他、包括、いない値。However, the maxValue parameter, which specifies the upper range returned number, is an exclusive, not an inclusive, value. つまり、メソッドの呼び出しNext(0, 100)0 ~ 99 の範囲演算子と not between 0 と 100 の値を返します。This means that the method call Next(0, 100) returns a value between 0 and 99, and not between 0 and 100.

使用することも、Randomなどのタスクを生成するためのクラスランダム T:System.Boolean 値生成、ランダムな浮動小数点値以外の 0 ~ 1 の範囲でを生成する64 ビットの整数の乱数、およびの一意の要素を配列またはコレクションからランダムに取得します。You can also use the Random class for such tasks as generating random T:System.Boolean values, generating random floating point values with a range other than 0 to 1, generating random 64-bit integers, and randomly retrieving a unique element from an array or collection. これらおよびその他の一般的なタスクは、次を参照してください、 System.Random を使用する.。For these and other common tasks, see the How do you use System.Random to… セクション。section.

独自のアルゴリズムの置換Substituting your own algorithm

継承することによって、独自の乱数を実装することができます、Randomクラスと乱数の生成アルゴリズムを指定します。You can implement your own random number generator by inheriting from the Random class and supplying your random number generation algorithm. オーバーライドする必要があります、独自のアルゴリズムを指定する、Sampleメソッドで、乱数生成アルゴリズムを実装します。To supply your own algorithm, you must override the Sample method, which implements the random number generation algorithm. オーバーライドすることも必要があります、 Next()Next(Int32, Int32)、およびNextBytesメソッドのオーバーライドを呼び出すことを確認するSampleメソッド。You should also override the Next(), Next(Int32, Int32), and NextBytes methods to ensure that they call your overridden Sample method. オーバーライドする必要はありません、Next(Int32)NextDoubleメソッド。You don't have to override the Next(Int32) and NextDouble methods.

派生する例については、Randomクラスし、その既定擬似乱数ジェネレーター、変更を参照してください、Sampleリファレンス ページです。For an example that derives from the Random class and modifies its default pseudo-random number generator, see the Sample reference page.

System.Random を使用するには.How do you use System.Random to…

次のセクションでは、説明し、ランダムな数値をアプリで使用する方法のいくつかのサンプル コードを提供します。The following sections discuss and provide sample code for some of the ways you might want to use random numbers in your app.

ランダムな値の同じシーケンスを取得します。Retrieve the same sequence of random values

ゲームのプレイとソフトウェア テスト シナリオで同じランダムな数値のシーケンスを生成することがあります。Sometimes you want to generate the same sequence of random numbers in software test scenarios and in game playing. ランダムな数値のシーケンスが同じテストを使用すると、回帰を検出し、バグの修正を確認できます。Testing with the same sequence of random numbers allows you to detect regressions and confirm bug fixes. ゲームで同じランダムな数値のシーケンスを使用して以前のゲームを再生することができます。Using the same sequence of random number in games allows you to replay previous games.

同じシード値を提供することで同じランダムな数値のシーケンスを生成することができます、Random(Int32)コンス トラクター。You can generate the same sequence of random numbers by providing the same seed value to the Random(Int32) constructor. シード値は、擬似乱数生成アルゴリズムの開始値を提供します。The seed value provides a starting value for the pseudo-random number generation algorithm. 次の例では、任意のシード値として 100100 をでインスタンス化する、Randomオブジェクト、20 個のランダムな浮動小数点値を表示およびシード値が引き続き発生します。The following example uses 100100 as an arbitrary seed value to instantiate the Random object, displays 20 random floating-point values, and persists the seed value. シード値を復元する、新しいランダムな番号ジェネレーターのインスタンスを作成し、20 同じのランダムな浮動小数点値を表示します。It then restores the seed value, instantiates a new random number generator, and displays the same 20 random floating-point values. 例も、異なるバージョンの .NET Framework 上で実行する場合に、ランダムな数値のさまざまなシーケンスを生成可能性がありますに注意してください。Note that the example may produce different sequences of random numbers if run on different versions of the .NET Framework.

using namespace System;
using namespace System::IO;

ref class RandomMethods
{
internal:
   static void ShowRandomNumbers(int seed)
   {
      Random^ rnd = gcnew Random(seed);
      for (int ctr = 0; ctr <= 20; ctr++)
         Console::WriteLine(rnd->NextDouble());
   }
   
   static void PersistSeed(int seed)
   {
      FileStream^ fs = gcnew FileStream(".\\seed.dat", FileMode::Create);
      BinaryWriter^ bin = gcnew BinaryWriter(fs);
      bin->Write(seed);
      bin->Close();
   }
   
   static void DisplayNewRandomNumbers()
   {
      FileStream^ fs = gcnew FileStream(".\\seed.dat", FileMode::Open);
      BinaryReader^ bin = gcnew BinaryReader(fs);
      int seed = bin->ReadInt32();
      bin->Close();
      
      Random^ rnd = gcnew Random(seed);
      for (int ctr = 0; ctr <= 20; ctr++)
         Console::WriteLine(rnd->NextDouble());
   }
};

void main()
{
   int seed = 100100;
   RandomMethods::ShowRandomNumbers(seed);
   Console::WriteLine();

   RandomMethods::PersistSeed(seed);

   RandomMethods::DisplayNewRandomNumbers();
}
// The example displays output like the following:
//       0.500193602172748
//       0.0209461245783354
//       0.465869495396442
//       0.195512794514891
//       0.928583675496552
//       0.729333720509584
//       0.381455668891527
//       0.0508996467343064
//       0.019261200921266
//       0.258578445417145
//       0.0177532266908107
//       0.983277184415272
//       0.483650274334313
//       0.0219647376900375
//       0.165910115077118
//       0.572085966622497
//       0.805291457942357
//       0.927985211335116
//       0.4228545699375
//       0.523320379910674
//       0.157783938645285
//       
//       0.500193602172748
//       0.0209461245783354
//       0.465869495396442
//       0.195512794514891
//       0.928583675496552
//       0.729333720509584
//       0.381455668891527
//       0.0508996467343064
//       0.019261200921266
//       0.258578445417145
//       0.0177532266908107
//       0.983277184415272
//       0.483650274334313
//       0.0219647376900375
//       0.165910115077118
//       0.572085966622497
//       0.805291457942357
//       0.927985211335116
//       0.4228545699375
//       0.523320379910674
//       0.157783938645285
using System;
using System.IO;

public class Example
{
   public static void Main()
   {
      int seed = 100100;
      ShowRandomNumbers(seed);
      Console.WriteLine();
      
      PersistSeed(seed);
      
      DisplayNewRandomNumbers(); 
   }
   
   private static void ShowRandomNumbers(int seed)
   {
      Random rnd = new Random(seed);
      for (int ctr = 0; ctr <= 20; ctr++)
         Console.WriteLine(rnd.NextDouble());
   }
   
   private static void PersistSeed(int seed)
   {
      FileStream fs = new FileStream(@".\seed.dat", FileMode.Create);
      BinaryWriter bin = new BinaryWriter(fs);
      bin.Write(seed);
      bin.Close();
   }
   
   private static void DisplayNewRandomNumbers()
   {
      FileStream fs = new FileStream(@".\seed.dat", FileMode.Open);
      BinaryReader bin = new BinaryReader(fs);
      int seed = bin.ReadInt32();
      bin.Close();
      
      Random rnd = new Random(seed);
      for (int ctr = 0; ctr <= 20; ctr++)
         Console.WriteLine(rnd.NextDouble());
   }
}
// The example displays output like the following:
//       0.500193602172748
//       0.0209461245783354
//       0.465869495396442
//       0.195512794514891
//       0.928583675496552
//       0.729333720509584
//       0.381455668891527
//       0.0508996467343064
//       0.019261200921266
//       0.258578445417145
//       0.0177532266908107
//       0.983277184415272
//       0.483650274334313
//       0.0219647376900375
//       0.165910115077118
//       0.572085966622497
//       0.805291457942357
//       0.927985211335116
//       0.4228545699375
//       0.523320379910674
//       0.157783938645285
//       
//       0.500193602172748
//       0.0209461245783354
//       0.465869495396442
//       0.195512794514891
//       0.928583675496552
//       0.729333720509584
//       0.381455668891527
//       0.0508996467343064
//       0.019261200921266
//       0.258578445417145
//       0.0177532266908107
//       0.983277184415272
//       0.483650274334313
//       0.0219647376900375
//       0.165910115077118
//       0.572085966622497
//       0.805291457942357
//       0.927985211335116
//       0.4228545699375
//       0.523320379910674
//       0.157783938645285
Imports System.IO

Module Example
   Public Sub Main()
      Dim seed As Integer = 100100
      ShowRandomNumbers(seed)
      Console.WriteLine()
      
      PersistSeed(seed)
      
      DisplayNewRandomNumbers() 
   End Sub
   
   Private Sub ShowRandomNumbers(seed As Integer)
      Dim rnd As New Random(seed)
      For ctr As Integer = 0 To 20
         Console.WriteLine(rnd.NextDouble())
      Next
   End Sub
   
   Private Sub PersistSeed(seed As Integer)
      Dim fs As New FileStream(".\seed.dat", FileMode.Create)
      Dim bin As New BinaryWriter(fs)
      bin.Write(seed)
      bin.Close()
   End Sub
   
   Private Sub DisplayNewRandomNumbers()
      Dim fs As New FileStream(".\seed.dat", FileMode.Open)
      Dim bin As New BinaryReader(fs)
      Dim seed As Integer = bin.ReadInt32()
      bin.Close()
      
      Dim rnd As New Random(seed)
      For ctr As Integer = 0 To 20
         Console.WriteLine(rnd.NextDouble())
      Next
   End Sub
End Module
' The example displays output like the following:
'       0.500193602172748
'       0.0209461245783354
'       0.465869495396442
'       0.195512794514891
'       0.928583675496552
'       0.729333720509584
'       0.381455668891527
'       0.0508996467343064
'       0.019261200921266
'       0.258578445417145
'       0.0177532266908107
'       0.983277184415272
'       0.483650274334313
'       0.0219647376900375
'       0.165910115077118
'       0.572085966622497
'       0.805291457942357
'       0.927985211335116
'       0.4228545699375
'       0.523320379910674
'       0.157783938645285
'       
'       0.500193602172748
'       0.0209461245783354
'       0.465869495396442
'       0.195512794514891
'       0.928583675496552
'       0.729333720509584
'       0.381455668891527
'       0.0508996467343064
'       0.019261200921266
'       0.258578445417145
'       0.0177532266908107
'       0.983277184415272
'       0.483650274334313
'       0.0219647376900375
'       0.165910115077118
'       0.572085966622497
'       0.805291457942357
'       0.927985211335116
'       0.4228545699375
'       0.523320379910674
'       0.157783938645285

乱数の一意のシーケンスを取得します。Retrieve unique sequences of random numbers

インスタンスに異なるシード値を提供する、Randomクラスにより各乱数ジェネレーターの値のさまざまなシーケンスを生成します。Providing different seed values to instances of the Random class causes each random number generator to produce a different sequence of values. シード値を明示的に呼び出していずれかで行うことができます、Random(Int32)コンス トラクター、または暗黙的に呼び出して、Random()コンス トラクター。You can provide a seed value either explicitly by calling the Random(Int32) constructor, or implicitly by calling the Random() constructor. ほとんどの開発者は、システム クロックを使用してパラメーターなしのコンス トラクターを呼び出します。Most developers call the parameterless constructor, which uses the system clock. 次の例では、このアプローチを使用して 2 つのインスタンスを作成するRandomインスタンス。The following example uses this approach to instantiate two Random instances. 各インスタンスは、一連の 10 個のランダムな整数を表示します。Each instance displays a series of 10 random integers.

using namespace System;
using namespace System::Threading;

void main()
{
   Console::WriteLine("Instantiating two random number generators...");
   Random^ rnd1 = gcnew Random();
   Thread::Sleep(2000);
   Random^ rnd2 = gcnew Random();
   
   Console::WriteLine("\nThe first random number generator:");
   for (int ctr = 1; ctr <= 10; ctr++)
      Console::WriteLine("   {0}", rnd1->Next());

   Console::WriteLine("\nThe second random number generator:");
   for (int ctr = 1; ctr <= 10; ctr++)
      Console::WriteLine("   {0}", rnd2->Next());
}
// The example displays output like the following:
//       Instantiating two random number generators...
//       
//       The first random number generator:
//          643164361
//          1606571630
//          1725607587
//          2138048432
//          496874898
//          1969147632
//          2034533749
//          1840964542
//          412380298
//          47518930
//       
//       The second random number generator:
//          1251659083
//          1514185439
//          1465798544
//          517841554
//          1821920222
//          195154223
//          1538948391
//          1548375095
//          546062716
//          897797880
using System;
using System.Threading;

public class Example
{
   public static void Main()
   {
      Console.WriteLine("Instantiating two random number generators...");
      Random rnd1 = new Random();
      Thread.Sleep(2000);
      Random rnd2 = new Random();
      
      Console.WriteLine("\nThe first random number generator:");
      for (int ctr = 1; ctr <= 10; ctr++)
         Console.WriteLine("   {0}", rnd1.Next());

      Console.WriteLine("\nThe second random number generator:");
      for (int ctr = 1; ctr <= 10; ctr++)
         Console.WriteLine("   {0}", rnd2.Next());
   }
}
// The example displays output like the following:
//       Instantiating two random number generators...
//       
//       The first random number generator:
//          643164361
//          1606571630
//          1725607587
//          2138048432
//          496874898
//          1969147632
//          2034533749
//          1840964542
//          412380298
//          47518930
//       
//       The second random number generator:
//          1251659083
//          1514185439
//          1465798544
//          517841554
//          1821920222
//          195154223
//          1538948391
//          1548375095
//          546062716
//          897797880
Imports System.Threading

Module Example
   Public Sub Main()
      Console.WriteLine("Instantiating two random number generators...")
      Dim rnd1 As New Random()
      Thread.Sleep(2000)
      Dim rnd2 As New Random()
      Console.WriteLine()
      
      Console.WriteLine("The first random number generator:")
      For ctr As Integer = 1 To 10
         Console.WriteLine("   {0}", rnd1.Next())
      Next  
      Console.WriteLine()
       
      Console.WriteLine("The second random number generator:")
      For ctr As Integer = 1 To 10
         Console.WriteLine("   {0}", rnd2.Next())
      Next   
   End Sub
End Module
' The example displays output like the following:
'       Instantiating two random number generators...
'       
'       The first random number generator:
'          643164361
'          1606571630
'          1725607587
'          2138048432
'          496874898
'          1969147632
'          2034533749
'          1840964542
'          412380298
'          47518930
'       
'       The second random number generator:
'          1251659083
'          1514185439
'          1465798544
'          517841554
'          1821920222
'          195154223
'          1538948391
'          1548375095
'          546062716
'          897797880

ただし、有限の解像度のため、システム クロックが約 15 ミリ秒未満である時間の相違点を検出しません。However, because of its finite resolution, the system clock doesn't detect time differences that are less than approximately 15 milliseconds. そのため、コードを呼び出す場合、 Random() 2 つのインスタンスを作成するオーバー ロードRandomする可能性がありますが誤ってするオブジェクトを提供する、同一のシード値を連続してオブジェクトします。Therefore, if your code calls the Random() overload to instantiate two Random objects in succession, you might inadvertently be providing the objects with identical seed values. 前の例では、これを参照してくださいをコメント アウト、Thread.Sleepメソッドの呼び出しとコンパイルと実行の例をもう一度です。To see this in the previous example, comment out the Thread.Sleep method call, and compile and run the example again.

これが事態を防ぐためにお勧め、1 つのインスタンスを作成するRandom複数のではなくオブジェクトします。To prevent this from happening, we recommend that you instantiate a single Random object rather than multiple ones. ただし、Randomいないスレッド セーフであるためにアクセスする場合は、いくつかの同期デバイスを使用する必要があります、Random詳細については複数のスレッドからのインスタンスは、「 、ランダムなクラスおよびスレッドの安全性この以前トピックです。However, since Random isn't thread safe, you must use some synchronization device if you access a Random instance from multiple threads; for more information, see The Random class and thread safety earlier in this topic. など、遅延メカニズムを使用する代わりに、Sleepメソッドの前の例では、インスタンス化には、15 を超えるミリ秒間隔が発生することを確認するために使用します。Alternately, you can use a delay mechanism, such as the Sleep method used in the previous example, to ensure that the instantiations occur more than 15 millisecond apart.

指定した範囲の整数を取得します。Retrieve integers in a specified range

指定した範囲の整数を取得するには呼び出すことによって、Next(Int32, Int32)メソッドは、返される乱数ジェネレーターの数値の上限と下限を指定することができます。You can retrieve integers in a specified range by calling the Next(Int32, Int32) method, which lets you specify both the lower and the upper bound of the numbers you'd like the random number generator to return. 上限は、排他、包括、いない値です。The upper bound is an exclusive, not an inclusive, value. つまり、メソッドによって返される値の範囲に含まれていません。That is, it isn't included in the range of values returned by the method. 次の例では、このメソッドを使用して、-10 ~ 10 の間の整数の乱数を生成します。The following example uses this method to generate random integers between -10 and 10. 1 つの値として、目的の値よりも大きい値である、11 を指定しているメモのmaxValueメソッド呼び出しの引数。Note that it specifies 11, which is one greater than the desired value, as the value of the maxValue argument in the method call.

using namespace System;

void main()
{
   Random^ rnd = gcnew Random();
   for (int ctr = 1; ctr <= 15; ctr++) {
      Console::Write("{0,3}    ", rnd->Next(-10, 11));
      if(ctr % 5 == 0) Console::WriteLine();
   }
}
// The example displays output like the following:
//        -2     -5     -1     -2     10
//        -3      6     -4     -8      3
//        -7     10      5     -2      4
using System;

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      for (int ctr = 1; ctr <= 15; ctr++) {
         Console.Write("{0,3}    ", rnd.Next(-10, 11));
         if(ctr % 5 == 0) Console.WriteLine();
      }   
   }
}
// The example displays output like the following:
//        -2     -5     -1     -2     10
//        -3      6     -4     -8      3
//        -7     10      5     -2      4
Module Example
   Public Sub Main()
      Dim rnd As New Random()
      For ctr As Integer = 1 To 15
         Console.Write("{0,3}    ", rnd.Next(-10, 11))
         If ctr Mod 5 = 0 Then Console.WriteLine()
      Next   
   End Sub
End Module
' The example displays output like the following:
'        -2     -5     -1     -2     10
'        -3      6     -4     -8      3
'        -7     10      5     -2      4

指定した桁数を持つ整数を取得します。Retrieve integers with a specified number of digits

呼び出すことができます、Next(Int32, Int32)指定した桁数で数値を取得します。You can call the Next(Int32, Int32) method to retrieve numbers with a specified number of digits. 呼び出すこと (1000 から 9999 の範囲数) の 4 桁の番号を取得するには、たとえば、Next(Int32, Int32)メソッドをminValue値は 1000 とmaxValueとして次の例は、10000 の値。For example, to retrieve numbers with four digits (that is, numbers that range from 1000 to 9999), you call the Next(Int32, Int32) method with a minValue value of 1000 and a maxValue value of 10000, as the following example shows.

using namespace System;

void main()
{
   Random^ rnd = gcnew Random();
   for (int ctr = 1; ctr <= 50; ctr++) {
      Console::Write("{0,3}   ", rnd->Next(1000, 10000));
      if(ctr % 10 == 0) Console::WriteLine();
   }   
}
// The example displays output like the following:
//    9570    8979    5770    1606    3818    4735    8495    7196    7070    2313
//    5279    6577    5104    5734    4227    3373    7376    6007    8193    5540
//    7558    3934    3819    7392    1113    7191    6947    4963    9179    7907
//    3391    6667    7269    1838    7317    1981    5154    7377    3297    5320
//    9869    8694    2684    4949    2999    3019    2357    5211    9604    2593
using System;

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      for (int ctr = 1; ctr <= 50; ctr++) {
         Console.Write("{0,3}    ", rnd.Next(1000, 10000));
         if(ctr % 10 == 0) Console.WriteLine();
      }   
   }
}
// The example displays output like the following:
//    9570    8979    5770    1606    3818    4735    8495    7196    7070    2313
//    5279    6577    5104    5734    4227    3373    7376    6007    8193    5540
//    7558    3934    3819    7392    1113    7191    6947    4963    9179    7907
//    3391    6667    7269    1838    7317    1981    5154    7377    3297    5320
//    9869    8694    2684    4949    2999    3019    2357    5211    9604    2593
Module Example
   Public Sub Main()
      Dim rnd As New Random()
      For ctr As Integer = 1 To 50
         Console.Write("{0,3}    ", rnd.Next(1000, 10000))
         If ctr Mod 10 = 0 Then Console.WriteLine()
      Next   
   End Sub
End Module
' The example displays output like the following:
'    9570    8979    5770    1606    3818    4735    8495    7196    7070    2313
'    5279    6577    5104    5734    4227    3373    7376    6007    8193    5540
'    7558    3934    3819    7392    1113    7191    6947    4963    9179    7907
'    3391    6667    7269    1838    7317    1981    5154    7377    3297    5320
'    9869    8694    2684    4949    2999    3019    2357    5211    9604    2593

指定した範囲の浮動小数点値を取得します。Retrieve floating-point values in a specified range

NextDoubleメソッド 0 を返しますランダムな浮動小数点値の範囲を 1 未満にします。The NextDouble method returns random floating-point values that range from 0 to less than 1. ただし、多くの場合、たいその他のいくつかの範囲にランダムな値を生成します。However, you'll often want to generate random values in some other range.

によって返される数に必要な開始時間間隔と 0 の違いを追加するには必要な最小値と最大値までの間隔が 1 の場合、NextDoubleメソッド。If the interval between the minimum and maximum desired values is 1, you can add the difference between the desired starting interval and 0 to the number returned by the NextDouble method. 次の例は、-1 から 0 までの 10 個の乱数を生成します。The following example does this to generate 10 random numbers between -1 and 0.

using namespace System;

void main()
{
   Random^ rnd = gcnew Random();
   for (int ctr = 1; ctr <= 10; ctr++)
      Console::WriteLine(rnd->NextDouble() - 1);
}
// The example displays output like the following:
//       -0.930412760437658
//       -0.164699016215605
//       -0.9851692803135
//       -0.43468508843085
//       -0.177202483255976
//       -0.776813320245972
//       -0.0713201854710096
//       -0.0912875561468711
//       -0.540621722368813
//       -0.232211863730201
using System;

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      for (int ctr = 1; ctr <= 10; ctr++)
         Console.WriteLine(rnd.NextDouble() - 1);
   }
}
// The example displays output like the following:
//       -0.930412760437658
//       -0.164699016215605
//       -0.9851692803135
//       -0.43468508843085
//       -0.177202483255976
//       -0.776813320245972
//       -0.0713201854710096
//       -0.0912875561468711
//       -0.540621722368813
//       -0.232211863730201
Module Example
   Public Sub Main()
      Dim rnd As New Random()
      For ctr As Integer = 1 To 10
         Console.WriteLine(rnd.NextDouble() - 1)
      Next
   End Sub
End Module
' The example displays output like the following:
'       -0.930412760437658
'       -0.164699016215605
'       -0.9851692803135
'       -0.43468508843085
'       -0.177202483255976
'       -0.776813320245972
'       -0.0713201854710096
'       -0.0912875561468711
'       -0.540621722368813
'       -0.232211863730201

浮動小数点乱数を生成する下限は 0 が、上限は 1 より大きい (または、負の数値の場合の下限の境界が-1 未満です、上限は 0)、0 以外のバインドでランダムな数値を乗算します。To generate random floating-point numbers whose lower bound is 0 but upper bound is greater than 1 (or, in the case of negative numbers, whose lower bound is less than -1 and upper bound is 0), multiply the random number by the non-zero bound. 次の例はこれを 2,000万浮動小数点乱数を生成する範囲 0 ~Int64.MaxValueします。The following example does this to generate 20 million random floating-point numbers that range from 0 to Int64.MaxValue. も、メソッドによって生成されるランダムな値の分布を表示します。In also displays the distribution of the random values generated by the method.

using namespace System;

void main()
{
   const Int64 ONE_TENTH = 922337203685477581;
   Random^ rnd = gcnew Random();
   double number;
   array<int>^ count = gcnew array<int>(10);
   
   // Generate 20 million integer values between.
   for (int ctr = 1; ctr <= 20000000; ctr++) {
      number = rnd->NextDouble() * Int64::MaxValue;
      // Categorize random numbers into 10 groups.
      int value = (int) (number / ONE_TENTH);
      count[value]++;
   }

   // Display breakdown by range.
   Console::WriteLine("{0,28} {1,32}   {2,7}\n", "Range", "Count", "Pct.");
   for (int ctr = 0; ctr <= 9; ctr++)
      Console::WriteLine("{0,25:N0}-{1,25:N0}  {2,8:N0}   {3,7:P2}", ctr * ONE_TENTH,
                         ctr < 9 ? ctr * ONE_TENTH + ONE_TENTH - 1 : Int64::MaxValue,
                         count[ctr], count[ctr]/20000000.0);
}
// The example displays output like the following:
//                           Range                            Count      Pct.
//    
//                            0-  922,337,203,685,477,580  1,996,148    9.98 %
//      922,337,203,685,477,581-1,844,674,407,370,955,161  2,000,293   10.00 %
//    1,844,674,407,370,955,162-2,767,011,611,056,432,742  2,000,094   10.00 %
//    2,767,011,611,056,432,743-3,689,348,814,741,910,323  2,000,159   10.00 %
//    3,689,348,814,741,910,324-4,611,686,018,427,387,904  1,999,552   10.00 %
//    4,611,686,018,427,387,905-5,534,023,222,112,865,485  1,998,248    9.99 %
//    5,534,023,222,112,865,486-6,456,360,425,798,343,066  2,000,696   10.00 %
//    6,456,360,425,798,343,067-7,378,697,629,483,820,647  2,001,637   10.01 %
//    7,378,697,629,483,820,648-8,301,034,833,169,298,228  2,002,870   10.01 %
//    8,301,034,833,169,298,229-9,223,372,036,854,775,807  2,000,303   10.00 %
using System;

public class Example
{
   public static void Main()
   {
      const long ONE_TENTH = 922337203685477581;

      Random rnd = new Random();
      double number;
      int[] count = new int[10];
      
      // Generate 20 million integer values between.
      for (int ctr = 1; ctr <= 20000000; ctr++) {
         number = rnd.NextDouble() * Int64.MaxValue;
         // Categorize random numbers into 10 groups.
         count[(int) (number / ONE_TENTH)]++;
      }
      // Display breakdown by range.
      Console.WriteLine("{0,28} {1,32}   {2,7}\n", "Range", "Count", "Pct.");
      for (int ctr = 0; ctr <= 9; ctr++)
         Console.WriteLine("{0,25:N0}-{1,25:N0}  {2,8:N0}   {3,7:P2}", ctr * ONE_TENTH,
                            ctr < 9 ? ctr * ONE_TENTH + ONE_TENTH - 1 : Int64.MaxValue, 
                            count[ctr], count[ctr]/20000000.0);
   }
}
// The example displays output like the following:
//                           Range                            Count      Pct.
//    
//                            0-  922,337,203,685,477,580  1,996,148    9.98 %
//      922,337,203,685,477,581-1,844,674,407,370,955,161  2,000,293   10.00 %
//    1,844,674,407,370,955,162-2,767,011,611,056,432,742  2,000,094   10.00 %
//    2,767,011,611,056,432,743-3,689,348,814,741,910,323  2,000,159   10.00 %
//    3,689,348,814,741,910,324-4,611,686,018,427,387,904  1,999,552   10.00 %
//    4,611,686,018,427,387,905-5,534,023,222,112,865,485  1,998,248    9.99 %
//    5,534,023,222,112,865,486-6,456,360,425,798,343,066  2,000,696   10.00 %
//    6,456,360,425,798,343,067-7,378,697,629,483,820,647  2,001,637   10.01 %
//    7,378,697,629,483,820,648-8,301,034,833,169,298,228  2,002,870   10.01 %
//    8,301,034,833,169,298,229-9,223,372,036,854,775,807  2,000,303   10.00 %
Module Example
   Public Sub Main()
      Const ONE_TENTH As Long = 922337203685477581

      Dim rnd As New Random()
      Dim number As Long
      Dim count(9) As Integer
      
      ' Generate 20 million integer values.
      For ctr As Integer = 1 To 20000000
         number = CLng(rnd.NextDouble() * Int64.MaxValue)
         ' Categorize random numbers.
         count(CInt(number \ ONE_TENTH)) += 1
      Next
      ' Display breakdown by range.
      Console.WriteLine("{0,28} {1,32}   {2,7}", "Range", "Count", "Pct.")
      Console.WriteLine()
      For ctr As Integer = 0 To 9
         Console.WriteLine("{0,25:N0}-{1,25:N0}  {2,8:N0}   {3,7:P2}", ctr * ONE_TENTH,
                            If(ctr < 9, ctr * ONE_TENTH + ONE_TENTH - 1, Int64.MaxValue), 
                            count(ctr), count(ctr)/20000000)
      Next
   End Sub
End Module
' The example displays output like the following:
'                           Range                            Count      Pct.
'    
'                            0-  922,337,203,685,477,580  1,996,148    9.98 %
'      922,337,203,685,477,581-1,844,674,407,370,955,161  2,000,293   10.00 %
'    1,844,674,407,370,955,162-2,767,011,611,056,432,742  2,000,094   10.00 %
'    2,767,011,611,056,432,743-3,689,348,814,741,910,323  2,000,159   10.00 %
'    3,689,348,814,741,910,324-4,611,686,018,427,387,904  1,999,552   10.00 %
'    4,611,686,018,427,387,905-5,534,023,222,112,865,485  1,998,248    9.99 %
'    5,534,023,222,112,865,486-6,456,360,425,798,343,066  2,000,696   10.00 %
'    6,456,360,425,798,343,067-7,378,697,629,483,820,647  2,001,637   10.01 %
'    7,378,697,629,483,820,648-8,301,034,833,169,298,228  2,002,870   10.01 %
'    8,301,034,833,169,298,229-9,223,372,036,854,775,807  2,000,303   10.00 %

などの任意の 2 つの値の間で浮動小数点乱数を生成する、Next(Int32, Int32)メソッドは、整数の場合は、次の数式を使用します。To generate random floating-point numbers between two arbitrary values, like the Next(Int32, Int32) method does for integers, use the following formula:

Random.NextDouble() * (maxValue - minValue) + minValue  

次の例では、11.0 に 10.0 から 100万の乱数の範囲を生成し、その分布が表示されます。The following example generates 1 million random numbers that range from 10.0 to 11.0, and displays their distribution.

using namespace System;

void main()
{
   Random^ rnd = gcnew Random();
   int lowerBound = 10;
   int upperBound = 11;
   array<int>^ range = gcnew array<int>(10);
   for (int ctr = 1; ctr <= 1000000; ctr++) {
      Double value = rnd->NextDouble() * (upperBound - lowerBound) + lowerBound;
      range[(int) Math::Truncate((value - lowerBound) * 10)]++;
   }
   
   for (int ctr = 0; ctr <= 9; ctr++) {
      Double lowerRange = 10 + ctr * .1;
      Console::WriteLine("{0:N1} to {1:N1}: {2,8:N0}  ({3,7:P2})",
                         lowerRange, lowerRange + .1, range[ctr],
                         range[ctr] / 1000000.0);
   } 
}
// The example displays output like the following:
//       10.0 to 10.1:   99,929  ( 9.99 %)
//       10.1 to 10.2:  100,189  (10.02 %)
//       10.2 to 10.3:   99,384  ( 9.94 %)
//       10.3 to 10.4:  100,240  (10.02 %)
//       10.4 to 10.5:   99,397  ( 9.94 %)
//       10.5 to 10.6:  100,580  (10.06 %)
//       10.6 to 10.7:  100,293  (10.03 %)
//       10.7 to 10.8:  100,135  (10.01 %)
//       10.8 to 10.9:   99,905  ( 9.99 %)
//       10.9 to 11.0:   99,948  ( 9.99 %)
using System;

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      int lowerBound = 10;
      int upperBound = 11;
      int[] range = new int[10];
      for (int ctr = 1; ctr <= 1000000; ctr++) {
         Double value = rnd.NextDouble() * (upperBound - lowerBound) + lowerBound;
         range[(int) Math.Truncate((value - lowerBound) * 10)]++; 
      }
      
      for (int ctr = 0; ctr <= 9; ctr++) {
         Double lowerRange = 10 + ctr * .1;
         Console.WriteLine("{0:N1} to {1:N1}: {2,8:N0}  ({3,7:P2})", 
                           lowerRange, lowerRange + .1, range[ctr], 
                           range[ctr] / 1000000.0);
      } 
   }
}
// The example displays output like the following:
//       10.0 to 10.1:   99,929  ( 9.99 %)
//       10.1 to 10.2:  100,189  (10.02 %)
//       10.2 to 10.3:   99,384  ( 9.94 %)
//       10.3 to 10.4:  100,240  (10.02 %)
//       10.4 to 10.5:   99,397  ( 9.94 %)
//       10.5 to 10.6:  100,580  (10.06 %)
//       10.6 to 10.7:  100,293  (10.03 %)
//       10.7 to 10.8:  100,135  (10.01 %)
//       10.8 to 10.9:   99,905  ( 9.99 %)
//       10.9 to 11.0:   99,948  ( 9.99 %)
Module Example
   Public Sub Main()
      Dim rnd As New Random()
      Dim lowerBound As Integer = 10
      Dim upperBound As Integer = 11
      Dim range(9) As Integer
      For ctr As Integer = 1 To 1000000
         Dim value As Double = rnd.NextDouble() * (upperBound - lowerBound) + lowerBound
         range(CInt(Math.Truncate((value - lowerBound) * 10))) += 1 
      Next
      
      For ctr As Integer = 0 To 9
         Dim lowerRange As Double = 10 + ctr * .1
         Console.WriteLine("{0:N1} to {1:N1}: {2,8:N0}  ({3,7:P2})", 
                           lowerRange, lowerRange + .1, range(ctr), 
                           range(ctr) / 1000000.0)
      Next 
   End Sub
End Module
' The example displays output like the following:
'       10.0 to 10.1:   99,929  ( 9.99 %)
'       10.1 to 10.2:  100,189  (10.02 %)
'       10.2 to 10.3:   99,384  ( 9.94 %)
'       10.3 to 10.4:  100,240  (10.02 %)
'       10.4 to 10.5:   99,397  ( 9.94 %)
'       10.5 to 10.6:  100,580  (10.06 %)
'       10.6 to 10.7:  100,293  (10.03 %)
'       10.7 to 10.8:  100,135  (10.01 %)
'       10.8 to 10.9:   99,905  ( 9.99 %)
'       10.9 to 11.0:   99,948  ( 9.99 %)

ランダムなブール値を生成します。Generate random Boolean values

Randomクラスを生成するメソッドを提供しませんBoolean値。The Random class doesn't provide methods that generate Boolean values. ただし、独自のクラスまたはそのメソッドを定義できます。However, you can define your own class or method to do that. 次の例では、クラスを定義するBooleanGenerator、単一のメソッドとNextBooleanします。The following example defines a class, BooleanGenerator, with a single method, NextBoolean. BooleanGeneratorストア クラス、Random秘密の変数としてのオブジェクト。The BooleanGenerator class stores a Random object as a private variable. NextBooleanメソッドの呼び出し、Random.Next(Int32, Int32)メソッドにより、結果と、Convert.ToBoolean(Int32)メソッド。The NextBoolean method calls the Random.Next(Int32, Int32) method and passes the result to the Convert.ToBoolean(Int32) method. ランダムな数の上限を指定する引数として 2 が使用されることに注意してください。Note that 2 is used as the argument to specify the upper bound of the random number. これは、排他的な値であるため、メソッドの呼び出しは、0 または 1 を返します。Since this is an exclusive value, the method call returns either 0 or 1.

using namespace System;

public ref class BooleanGenerator
{
   private:
      Random^ rnd;

   public:
      BooleanGenerator()
      {
         rnd = gcnew Random();
      }

      bool NextBoolean()
      {
         return Convert::ToBoolean(rnd->Next(0, 2));
      }
};

void main()
{
   // Instantiate the Boolean generator.
   BooleanGenerator^ boolGen = gcnew BooleanGenerator();
   int totalTrue = 0, totalFalse = 0;
   
   // Generate 1,0000 random Booleans, and keep a running total.
   for (int ctr = 0; ctr < 1000000; ctr++) {
       bool value = boolGen->NextBoolean();
       if (value)
          totalTrue++;
       else
          totalFalse++;
   }
   Console::WriteLine("Number of true values:  {0,7:N0} ({1:P3})",
                      totalTrue,
                      ((double) totalTrue)/(totalTrue + totalFalse));
   Console::WriteLine("Number of false values: {0,7:N0} ({1:P3})",
                     totalFalse, 
                     ((double) totalFalse)/(totalTrue + totalFalse));
}

// The example displays output like the following:
//       Number of true values:  500,004 (50.000 %)
//       Number of false values: 499,996 (50.000 %)
using System;

public class Example
{
   public static void Main()
   {
      // Instantiate the Boolean generator.
      BooleanGenerator boolGen = new BooleanGenerator();
      int totalTrue = 0, totalFalse = 0;
      
      // Generate 1,0000 random Booleans, and keep a running total.
      for (int ctr = 0; ctr < 1000000; ctr++) {
          bool value = boolGen.NextBoolean();
          if (value)
             totalTrue++;
          else
             totalFalse++;
      }
      Console.WriteLine("Number of true values:  {0,7:N0} ({1:P3})", 
                        totalTrue, 
                        ((double) totalTrue)/(totalTrue + totalFalse));
      Console.WriteLine("Number of false values: {0,7:N0} ({1:P3})", 
                        totalFalse, 
                        ((double) totalFalse)/(totalTrue + totalFalse));
   }
}

public class BooleanGenerator
{
   Random rnd;
   
   public BooleanGenerator()
   {
      rnd = new Random();
   }

   public bool NextBoolean()
   {
      return Convert.ToBoolean(rnd.Next(0, 2));
   }
}
// The example displays output like the following:
//       Number of true values:  500,004 (50.000 %)
//       Number of false values: 499,996 (50.000 %)
Module Example
   Public Sub Main()
      ' Instantiate the Boolean generator.
      Dim boolGen As New BooleanGenerator()
      Dim totalTrue, totalFalse As Integer 
      
      ' Generate 1,0000 random Booleans, and keep a running total.
      For ctr As Integer = 0 To 9999999
          Dim value As Boolean = boolGen.NextBoolean()
          If value Then
             totalTrue += 1
          Else
             totalFalse += 1
          End If
      Next
      Console.WriteLine("Number of true values:  {0,7:N0} ({1:P3})", 
                        totalTrue, 
                        totalTrue/(totalTrue + totalFalse))
      Console.WriteLine("Number of false values: {0,7:N0} ({1:P3})", 
                        totalFalse, 
                        totalFalse/(totalTrue + totalFalse))
   End Sub                     
End Module

Public Class BooleanGenerator
   Dim rnd As Random
   
   Public Sub New()
      rnd = New Random()
   End Sub

   Public Function NextBoolean() As Boolean
      Return Convert.ToBoolean(rnd.Next(0, 2))
   End Function
End Class
' The example displays the following output:
'       Number of true values:  500,004 (50.000 %)
'       Number of false values: 499,996 (50.000 %)

乱数を生成する別のクラスを作成する代わりにBoolean値、例では、1 つのメソッドが定義だけでした。Instead of creating a separate class to generate random Boolean values, the example could simply have defined a single method. ただし、その場合、Randomオブジェクトを新しいをインスタンス化を回避するためにクラス レベルの変数として定義する必要がありますRandom各メソッド呼び出し内のインスタンス。In that case, however, the Random object should have been defined as a class-level variable to avoid instantiating a new Random instance in each method call. Visual basic でとして Random インスタンスを定義することができます、静的変数、NextBooleanメソッド。In Visual Basic, the Random instance can be defined as a Static variable in the NextBoolean method. 次の例は、実装を提供します。The following example provides an implementation.

using namespace System;

ref class Example
{
private:
   static Random^ rnd = gcnew Random();

public:
   static void Execute()
   {
      int totalTrue = 0, totalFalse = 0;
      
      // Generate 1,0000 random Booleans, and keep a running total.
      for (int ctr = 0; ctr < 1000000; ctr++) {
          bool value = NextBoolean();
          if (value)
             totalTrue++;
          else
             totalFalse++;
      }
      Console::WriteLine("Number of true values:  {0,7:N0} ({1:P3})",
                        totalTrue, 
                        ((double) totalTrue)/(totalTrue + totalFalse));
      Console::WriteLine("Number of false values: {0,7:N0} ({1:P3})",
                        totalFalse, 
                        ((double) totalFalse)/(totalTrue + totalFalse));
   }

   static bool NextBoolean()
   {
      return Convert::ToBoolean(rnd->Next(0, 2));
   }
};

void main()
{
   Example::Execute();
}
// The example displays output like the following:
//       Number of true values:  499,777 (49.978 %)
//       Number of false values: 500,223 (50.022 %)
using System;

public class Example
{
   private static Random rnd = new Random();

   public static void Main()
   {
      int totalTrue = 0, totalFalse = 0;
      
      // Generate 1,0000 random Booleans, and keep a running total.
      for (int ctr = 0; ctr < 1000000; ctr++) {
          bool value = NextBoolean();
          if (value)
             totalTrue++;
          else
             totalFalse++;
      }
      Console.WriteLine("Number of true values:  {0,7:N0} ({1:P3})", 
                        totalTrue, 
                        ((double) totalTrue)/(totalTrue + totalFalse));
      Console.WriteLine("Number of false values: {0,7:N0} ({1:P3})", 
                        totalFalse, 
                        ((double) totalFalse)/(totalTrue + totalFalse));
   }

   public static bool NextBoolean()
   {
      return Convert.ToBoolean(rnd.Next(0, 2));
   }
}
// The example displays output like the following:
//       Number of true values:  499,777 (49.978 %)
//       Number of false values: 500,223 (50.022 %)
Module Example
   Public Sub Main()
      Dim totalTrue, totalFalse As Integer 
      
      ' Generate 1,0000 random Booleans, and keep a running total.
      For ctr As Integer = 0 To 9999999
          Dim value As Boolean = NextBoolean()
          If value Then
             totalTrue += 1
          Else
             totalFalse += 1
          End If
      Next
      Console.WriteLine("Number of true values:  {0,7:N0} ({1:P3})", 
                        totalTrue, 
                        totalTrue/(totalTrue + totalFalse))
      Console.WriteLine("Number of false values: {0,7:N0} ({1:P3})", 
                        totalFalse, 
                        totalFalse/(totalTrue + totalFalse))
   End Sub 
                       
   Public Function NextBoolean() As Boolean
      Static rnd As New Random()
      Return Convert.ToBoolean(rnd.Next(0, 2))
   End Function
End Module
' The example displays the following output:
'       Number of true values:  499,777 (49.978 %)
'       Number of false values: 500,223 (50.022 %)

64 ビットの整数の乱数を生成します。Generate random 64-bit integers

オーバー ロード、Nextメソッドは、32 ビット整数を返します。The overloads of the Next method return 32-bit integers. ただし、場合によっては、64 ビット整数を使用する必要があります。However, in some cases, you might want to work with 64-bit integers. このことは次のように実行できます。You can do this as follows:

  1. 呼び出す、NextDouble取得倍精度浮動小数点値。Call the NextDouble method to retrieve a double-precision floating point value.

  2. その値に乗算Int64.MaxValueします。Multiply that value by Int64.MaxValue.

次の例では、この手法を使用して、20 件の長整数の乱数を生成するし、10 個のと同じグループ内に分類されています。The following example uses this technique to generate 20 million random long integers and categorizes them in 10 equal groups. 0 から、各グループ内の数をカウントすることによってランダムな数値の分布を評価し、Int64.MaxValueします。It then evaluates the distribution of the random numbers by counting the number in each group from 0 to Int64.MaxValue. 例の出力に示すよう番号が長整数の範囲を増減均等に分散されます。As the output from the example shows, the numbers are distributed more or less equally through the range of a long integer.

using namespace System;

void main()
{
   const Int64 ONE_TENTH = 922337203685477581;

   Random^ rnd = gcnew Random();
   Int64 number;
   array<int>^ count = gcnew array<int>(10);
   
   // Generate 20 million long integers.
   for (int ctr = 1; ctr <= 20000000; ctr++) {
      number = (Int64) (rnd->NextDouble() * Int64::MaxValue);
      // Categorize random numbers.
      count[(int) (number / ONE_TENTH)]++;
   }
   // Display breakdown by range.
   Console::WriteLine("{0,28} {1,32}   {2,7}\n", "Range", "Count", "Pct.");
   for (int ctr = 0; ctr <= 9; ctr++)
      Console::WriteLine("{0,25:N0}-{1,25:N0}  {2,8:N0}   {3,7:P2}", ctr * ONE_TENTH,
                         ctr < 9 ? ctr * ONE_TENTH + ONE_TENTH - 1 : Int64::MaxValue,
                         count[ctr], count[ctr]/20000000.0);
}
// The example displays output like the following:
//                           Range                            Count      Pct.
//    
//                            0-  922,337,203,685,477,580  1,996,148    9.98 %
//      922,337,203,685,477,581-1,844,674,407,370,955,161  2,000,293   10.00 %
//    1,844,674,407,370,955,162-2,767,011,611,056,432,742  2,000,094   10.00 %
//    2,767,011,611,056,432,743-3,689,348,814,741,910,323  2,000,159   10.00 %
//    3,689,348,814,741,910,324-4,611,686,018,427,387,904  1,999,552   10.00 %
//    4,611,686,018,427,387,905-5,534,023,222,112,865,485  1,998,248    9.99 %
//    5,534,023,222,112,865,486-6,456,360,425,798,343,066  2,000,696   10.00 %
//    6,456,360,425,798,343,067-7,378,697,629,483,820,647  2,001,637   10.01 %
//    7,378,697,629,483,820,648-8,301,034,833,169,298,228  2,002,870   10.01 %
//    8,301,034,833,169,298,229-9,223,372,036,854,775,807  2,000,303   10.00 %
using System;

public class Example
{
   public static void Main()
   {
      const long ONE_TENTH = 922337203685477581;

      Random rnd = new Random();
      long number;
      int[] count = new int[10];
      
      // Generate 20 million long integers.
      for (int ctr = 1; ctr <= 20000000; ctr++) {
         number = (long) (rnd.NextDouble() * Int64.MaxValue);
         // Categorize random numbers.
         count[(int) (number / ONE_TENTH)]++;
      }
      // Display breakdown by range.
      Console.WriteLine("{0,28} {1,32}   {2,7}\n", "Range", "Count", "Pct.");
      for (int ctr = 0; ctr <= 9; ctr++)
         Console.WriteLine("{0,25:N0}-{1,25:N0}  {2,8:N0}   {3,7:P2}", ctr * ONE_TENTH,
                            ctr < 9 ? ctr * ONE_TENTH + ONE_TENTH - 1 : Int64.MaxValue, 
                            count[ctr], count[ctr]/20000000.0);
   }
}
// The example displays output like the following:
//                           Range                            Count      Pct.
//    
//                            0-  922,337,203,685,477,580  1,996,148    9.98 %
//      922,337,203,685,477,581-1,844,674,407,370,955,161  2,000,293   10.00 %
//    1,844,674,407,370,955,162-2,767,011,611,056,432,742  2,000,094   10.00 %
//    2,767,011,611,056,432,743-3,689,348,814,741,910,323  2,000,159   10.00 %
//    3,689,348,814,741,910,324-4,611,686,018,427,387,904  1,999,552   10.00 %
//    4,611,686,018,427,387,905-5,534,023,222,112,865,485  1,998,248    9.99 %
//    5,534,023,222,112,865,486-6,456,360,425,798,343,066  2,000,696   10.00 %
//    6,456,360,425,798,343,067-7,378,697,629,483,820,647  2,001,637   10.01 %
//    7,378,697,629,483,820,648-8,301,034,833,169,298,228  2,002,870   10.01 %
//    8,301,034,833,169,298,229-9,223,372,036,854,775,807  2,000,303   10.00 %
Module Example
   Public Sub Main()
      Const ONE_TENTH As Long = 922337203685477581

      Dim rnd As New Random()
      Dim number As Long
      Dim count(9) As Integer
      
      ' Generate 20 million long integers.
      For ctr As Integer = 1 To 20000000
         number = CLng(rnd.NextDouble() * Int64.MaxValue)
         ' Categorize random numbers.
         count(CInt(number \ ONE_TENTH)) += 1
      Next
      ' Display breakdown by range.
      Console.WriteLine("{0,28} {1,32}   {2,7}", "Range", "Count", "Pct.")
      Console.WriteLine()
      For ctr As Integer = 0 To 9
         Console.WriteLine("{0,25:N0}-{1,25:N0}  {2,8:N0}   {3,7:P2}", ctr * ONE_TENTH,
                            If(ctr < 9, ctr * ONE_TENTH + ONE_TENTH - 1, Int64.MaxValue), 
                            count(ctr), count(ctr)/20000000)
      Next
   End Sub
End Module
' The example displays output like the following:
'                           Range                            Count      Pct.
'    
'                            0-  922,337,203,685,477,580  1,996,148    9.98 %
'      922,337,203,685,477,581-1,844,674,407,370,955,161  2,000,293   10.00 %
'    1,844,674,407,370,955,162-2,767,011,611,056,432,742  2,000,094   10.00 %
'    2,767,011,611,056,432,743-3,689,348,814,741,910,323  2,000,159   10.00 %
'    3,689,348,814,741,910,324-4,611,686,018,427,387,904  1,999,552   10.00 %
'    4,611,686,018,427,387,905-5,534,023,222,112,865,485  1,998,248    9.99 %
'    5,534,023,222,112,865,486-6,456,360,425,798,343,066  2,000,696   10.00 %
'    6,456,360,425,798,343,067-7,378,697,629,483,820,647  2,001,637   10.01 %
'    7,378,697,629,483,820,648-8,301,034,833,169,298,228  2,002,870   10.01 %
'    8,301,034,833,169,298,229-9,223,372,036,854,775,807  2,000,303   10.00 %

ビットの操作を使用する代替手法は、真の乱数を生成しません。An alternative technique that uses bit manipulation does not generate truly random numbers. この手法を呼び出すNext()2 つの整数、左シフト 1 で 32 ビット、および Or を生成することです。This technique calls Next() to generate two integers, left-shifts one by 32 bits, and ORs them together. この手法では、2 つの制限があります。This technique has two limitations:

  1. 31 ビットは符号ビットであるため、結果の長整数のビット 31 の値は常に 0 です。Because bit 31 is the sign bit, the value in bit 31 of the resulting long integer is always 0. これは、31 ビット、および論理和をランダムな 0 または 1、左シフトを生成することによって対処できますで元のランダムな long 整数。This can be addressed by generating a random 0 or 1, left-shifting it 31 bits, and ORing it with the original random long integer.

  2. 重大、ため、によって返される値の確率Next()の場合は 0 には存在する場合は、少数のランダムな数値範囲 0x0 0x00000000FFFFFFFF で。More seriously, because the probability that the value returned by Next() will be 0, there will be few if any random numbers in the range 0x0-0x00000000FFFFFFFF.

指定した範囲内のバイトを取得します。Retrieve bytes in a specified range

オーバー ロード、Nextメソッドを使用する乱数の範囲を指定できますが、NextBytesメソッドはありません。The overloads of the Next method allow you to specify the range of random numbers, but the NextBytes method does not. 次の例では、実装、NextBytesメソッドが返されるバイトの範囲を指定することができます。The following example implements a NextBytes method that lets you specify the range of the returned bytes. 定義、Random2クラスから派生したRandomオーバー ロードとそのNextBytesメソッド。It defines a Random2 class that derives from Random and overloads its NextBytes method.

using namespace System;

ref class Random2 : Random
{
public:
   Random2()
   {}

   Random2(int seed) : Random(seed)
   {}

   void NextBytes(array<Byte>^ bytes, Byte minValue, Byte maxValue)
   {
      for (int ctr = bytes->GetLowerBound(0); ctr <= bytes->GetUpperBound(0); ctr++)
         bytes[ctr] = (Byte) Next(minValue, maxValue);
   }
};

void main()
{
    Random2^ rnd = gcnew Random2();
    array<Byte>^ bytes = gcnew array<Byte>(10000);
    array<int>^ total = gcnew array<int>(101);
    rnd->NextBytes(bytes, 0, 101);

    // Calculate how many of each value we have.
    for each (Byte value in bytes)
       total[value]++;

    // Display the results.
    for (int ctr = 0; ctr < total->Length; ctr++) {
        Console::Write("{0,3}: {1,-3}   ", ctr, total[ctr]);
        if ((ctr + 1) % 5 == 0) Console::WriteLine();
    }
}
// The example displays output like the following:
//         0: 115     1: 119     2: 92      3: 98      4: 92
//         5: 102     6: 103     7: 84      8: 93      9: 116
//        10: 91     11: 98     12: 106    13: 91     14: 92
//        15: 101    16: 100    17: 96     18: 97     19: 100
//        20: 101    21: 106    22: 112    23: 82     24: 85
//        25: 102    26: 107    27: 98     28: 106    29: 102
//        30: 109    31: 108    32: 94     33: 101    34: 107
//        35: 101    36: 86     37: 100    38: 101    39: 102
//        40: 113    41: 95     42: 96     43: 89     44: 99
//        45: 81     46: 89     47: 105    48: 100    49: 85
//        50: 103    51: 103    52: 93     53: 89     54: 91
//        55: 97     56: 105    57: 97     58: 110    59: 86
//        60: 116    61: 94     62: 117    63: 98     64: 110
//        65: 93     66: 102    67: 100    68: 105    69: 83
//        70: 81     71: 97     72: 85     73: 70     74: 98
//        75: 100    76: 110    77: 114    78: 83     79: 90
//        80: 96     81: 112    82: 102    83: 102    84: 99
//        85: 81     86: 100    87: 93     88: 99     89: 118
//        90: 95     91: 124    92: 108    93: 96     94: 104
//        95: 106    96: 99     97: 99     98: 92     99: 99
//       100: 108
using System;

public class Example
{
   public static void Main()
   {
       Random2 rnd = new Random2();
       Byte[] bytes = new Byte[10000];
       int[] total = new int[101];
       rnd.NextBytes(bytes, 0, 101);
       
       // Calculate how many of each value we have.
       foreach (var value in bytes)
          total[value]++;
       
       // Display the results.
       for (int ctr = 0; ctr < total.Length; ctr++) {
           Console.Write("{0,3}: {1,-3}   ", ctr, total[ctr]);
           if ((ctr + 1) % 5 == 0) Console.WriteLine();
       }   
   }
}

public class Random2 : Random
{
   public Random2() : base()
   {}

   public Random2(int seed) : base(seed)
   {}

   public void NextBytes(byte[] bytes, byte minValue, byte maxValue)
   {
      for (int ctr = bytes.GetLowerBound(0); ctr <= bytes.GetUpperBound(0); ctr++)
         bytes[ctr] = (byte) Next(minValue, maxValue);
   }
}
// The example displays output like the following:
//         0: 115     1: 119     2: 92      3: 98      4: 92
//         5: 102     6: 103     7: 84      8: 93      9: 116
//        10: 91     11: 98     12: 106    13: 91     14: 92
//        15: 101    16: 100    17: 96     18: 97     19: 100
//        20: 101    21: 106    22: 112    23: 82     24: 85
//        25: 102    26: 107    27: 98     28: 106    29: 102
//        30: 109    31: 108    32: 94     33: 101    34: 107
//        35: 101    36: 86     37: 100    38: 101    39: 102
//        40: 113    41: 95     42: 96     43: 89     44: 99
//        45: 81     46: 89     47: 105    48: 100    49: 85
//        50: 103    51: 103    52: 93     53: 89     54: 91
//        55: 97     56: 105    57: 97     58: 110    59: 86
//        60: 116    61: 94     62: 117    63: 98     64: 110
//        65: 93     66: 102    67: 100    68: 105    69: 83
//        70: 81     71: 97     72: 85     73: 70     74: 98
//        75: 100    76: 110    77: 114    78: 83     79: 90
//        80: 96     81: 112    82: 102    83: 102    84: 99
//        85: 81     86: 100    87: 93     88: 99     89: 118
//        90: 95     91: 124    92: 108    93: 96     94: 104
//        95: 106    96: 99     97: 99     98: 92     99: 99
//       100: 108
Module Example
   Public Sub Main()
       Dim rnd As New Random2()
       Dim bytes(9999) As Byte
       Dim total(100) As Integer
       rnd.NextBytes(bytes, 0, 101)
       
       ' Calculate how many of each value we have.
       For Each value In bytes
          total(value) += 1
       Next
       
       ' Display the results.
       For ctr As Integer = 0 To total.Length - 1
           Console.Write("{0,3}: {1,-3}   ", ctr, total(ctr))
           If (ctr + 1) Mod 5 = 0 Then Console.WriteLine()
       Next   
   End Sub
End Module

Public Class Random2 : Inherits Random
   Public Sub New()
      MyBase.New()
   End Sub   

   Public Sub New(seed As Integer)
      MyBase.New(seed)
   End Sub

   Public Overloads Sub NextBytes(bytes() As Byte, 
                                  minValue As Byte, maxValue As Byte)
      For ctr As Integer = bytes.GetLowerbound(0) To bytes.GetUpperBound(0)
         bytes(ctr) = CByte(MyBase.Next(minValue, maxValue))
      Next
   End Sub
End Class 
' The example displays output like the following:
'         0: 115     1: 119     2: 92      3: 98      4: 92
'         5: 102     6: 103     7: 84      8: 93      9: 116
'        10: 91     11: 98     12: 106    13: 91     14: 92
'        15: 101    16: 100    17: 96     18: 97     19: 100
'        20: 101    21: 106    22: 112    23: 82     24: 85
'        25: 102    26: 107    27: 98     28: 106    29: 102
'        30: 109    31: 108    32: 94     33: 101    34: 107
'        35: 101    36: 86     37: 100    38: 101    39: 102
'        40: 113    41: 95     42: 96     43: 89     44: 99
'        45: 81     46: 89     47: 105    48: 100    49: 85
'        50: 103    51: 103    52: 93     53: 89     54: 91
'        55: 97     56: 105    57: 97     58: 110    59: 86
'        60: 116    61: 94     62: 117    63: 98     64: 110
'        65: 93     66: 102    67: 100    68: 105    69: 83
'        70: 81     71: 97     72: 85     73: 70     74: 98
'        75: 100    76: 110    77: 114    78: 83     79: 90
'        80: 96     81: 112    82: 102    83: 102    84: 99
'        85: 81     86: 100    87: 93     88: 99     89: 118
'        90: 95     91: 124    92: 108    93: 96     94: 104
'        95: 106    96: 99     97: 99     98: 92     99: 99
'       100: 108

NextBytes(Byte[], Byte, Byte)メソッドへの呼び出しをラップします、Next(Int32, Int32)メソッド最小値と最大値よりも大きい 1 つを指定します (この場合は、0 と 101) バイト配列で返されるようにします。The NextBytes(Byte[], Byte, Byte) method wraps a call to the Next(Int32, Int32) method and specifies the minimum value and one greater than the maximum value (in this case, 0 and 101) that we want returned in the byte array. 整数値がによって返されることを確認していますので、Nextの範囲内のメソッドは、Byteデータ型、おできます安全にキャストに (c#) に変換したり (Visual Basic) で整数からバイト。Because we are sure that the integer values returned by the Next method are within the range of the Byte data type, we can safely cast them (in C#) or convert them (in Visual Basic) from integers to bytes.

配列またはコレクションから要素をランダムに取得します。Retrieve an element from an array or collection at random

ランダムな数値は、多くの場合、配列またはコレクションから値を取得するインデックスとして機能します。Random numbers often serve as indexes to retrieve values from arrays or collections. ランダムなインデックス値を取得するを呼び出すことができます、Next(Int32, Int32)メソッドをおよびの値としての配列の下限値を使用してそのminValue引数と 1 つの値として、配列の上限を超えるそのmaxValue引数。To retrieve a random index value, you can call the Next(Int32, Int32) method, and use the lower bound of the array as the value of its minValue argument and one greater than the upper bound of the array as the value of its maxValue argument. これに相当の 0 から始まる配列の場合は、そのLengthプロパティ、またはいずれかによって返される値より大きい、Array.GetUpperBoundメソッド。For a zero-based array, this is equivalent to its Length property, or one greater than the value returned by the Array.GetUpperBound method. 次の例は、都市の配列からランダムに米国の州の都市の名前を取得します。The following example randomly retrieves the name of a city in the United States from an array of cities.

using namespace System;

void main()
{
   array<String^>^ cities = { "Atlanta", "Boston", "Chicago", "Detroit",
                              "Fort Wayne", "Greensboro", "Honolulu", "Indianapolis",
                              "Jersey City", "Kansas City", "Los Angeles",
                              "Milwaukee", "New York", "Omaha", "Philadelphia",
                              "Raleigh", "San Francisco", "Tulsa", "Washington" };
   Random^ rnd = gcnew Random();
   int index = rnd->Next(0, cities->Length);
   Console::WriteLine("Today's city of the day: {0}",
                      cities[index]);
}
// The example displays output like the following:
//   Today's city of the day: Honolulu
using System;

public class Example
{
   public static void Main()
   {
      String[] cities = { "Atlanta", "Boston", "Chicago", "Detroit", 
                          "Fort Wayne", "Greensboro", "Honolulu", "Indianapolis", 
                          "Jersey City", "Kansas City", "Los Angeles", 
                          "Milwaukee", "New York", "Omaha", "Philadelphia", 
                          "Raleigh", "San Francisco", "Tulsa", "Washington" };
      Random rnd = new Random();
      int index = rnd.Next(0, cities.Length);
      Console.WriteLine("Today's city of the day: {0}",
                        cities[index]);                           
   }
}
// The example displays output like the following:
//   Today's city of the day: Honolulu
Module Example
   Public Sub Main()
      Dim cities() As String = { "Atlanta", "Boston", "Chicago", "Detroit", 
                                 "Fort Wayne", "Greensboro", "Honolulu", "Indianapolis", 
                                 "Jersey City", "Kansas City", "Los Angeles", 
                                 "Milwaukee", "New York", "Omaha", "Philadelphia", 
                                 "Raleigh", "San Francisco", "Tulsa", "Washington" }
      Dim rnd As New Random()
      Dim index As Integer = rnd.Next(0, cities.Length)
      Console.WriteLine("Today's city of the day: {0}",
                        cities(index))                           
   End Sub
End Module
' The example displays output like the following:
'   Today's city of the day: Honolulu

配列またはコレクションからの一意の要素を取得します。Retrieve a unique element from an array or collection

乱数ジェネレーターは、重複する値を常に返すことができます。A random number generator can always return duplicate values. 番号の範囲が小さくなります。 または、生成された値の数が大きくなる、重複の確率が大きくなります。As the range of numbers becomes smaller or the number of values generated becomes larger, the probability of duplicates grows. ランダムな値は一意である必要があります、他の番号は、パフォーマンスが低下ますます重複を補正するために生成されます。If random values must be unique, more numbers are generated to compensate for duplicates, resulting in increasingly poor performance.

このシナリオを処理するための手法を数多くあります。There are a number of techniques to handle this scenario. 1 つの一般的な解決策では、配列やコレクションを取得する値を格納する浮動小数点乱数を格納する並列配列を作成します。One common solution is to create an array or collection that contains the values to be retrieved, and a parallel array that contains random floating-point numbers. 2 番目の配列はランダムな数値では、最初の配列の作成時に設定されます。 およびArray.Sort(Array, Array)メソッドは並列配列の値を使用して、最初の配列を並べ替えに使用します。The second array is populated with random numbers at the time the first array is created, and the Array.Sort(Array, Array) method is used to sort the first array by using the values in the parallel array.

など、ソリティア ゲームを開発する場合に各カードが 1 回だけ使用されるようにします。For example, if you're developing a Solitaire game, you want to ensure that each card is used only once. カードとカードが処理済みかどうかを追跡を取得する乱数を生成するには、代わりに、デッキの並べ替えに使用できるランダムな数値の並列配列を作成できます。Instead of generating random numbers to retrieve a card and tracking whether that card has already been dealt, you can create a parallel array of random numbers that can be used to sort the deck. デッキが並べ替えられると、アプリは次のカード デッキでのインデックスを示しますへのポインターを維持できます。Once the deck is sorted, your app can maintain a pointer to indicate the index of the next card on the deck.

このアプローチの例を次に示します。The following example illustrates this approach. 定義、Cardクラスとトランプを表すDealerトランプのシャッフルを処理するクラス。It defines a Card class that represents a playing card and a Dealer class that deals a deck of shuffled cards. Dealerクラスのコンス トラクターは 2 つの配列を設定します、deckクラス スコープを持つと、すべてのカード デッキ; とローカルを表す配列orderを持つ同じ数の要素の配列、deck配列とは設定されます。ランダムに生成されたDouble値。The Dealer class constructor populates two arrays: a deck array that has class scope and that represents all the cards in the deck; and a local order array that has the same number of elements as the deck array and is populated with randomly generated Double values. Array.Sort(Array, Array)並べ替えメソッドが呼び出されてから、deck内の値に基づいて配列、order配列。The Array.Sort(Array, Array) method is then called to sort the deck array based on the values in the order array.

using namespace System;

public enum class Suit { Hearts, Diamonds, Spades, Clubs };

public enum class FaceValue  { Ace = 1, Two, Three, Four, Five, Six,
                               Seven, Eight, Nine, Ten, Jack, Queen,
                               King };

// A class that represents an individual card in a playing deck.
ref class Card
{
public:
   Suit Suit;
   FaceValue FaceValue;
   
   String^ ToString() override
   {
      return String::Format("{0:F} of {1:F}", this->FaceValue, this->Suit);
   }
};

ref class Dealer
{
private:
   Random^ rnd;
   // A deck of cards, without Jokers.
   array<Card^>^ deck = gcnew array<Card^>(52);
   // Parallel array for sorting cards.
   array<Double>^ order = gcnew array<Double>(52);
   // A pointer to the next card to deal.
   int ptr = 0;
   // A flag to indicate the deck is used.
   bool mustReshuffle = false;
   
public:
   Dealer()
   {
      rnd = gcnew Random();
      // Initialize the deck.
      int deckCtr = 0;
      for each (auto suit in Enum::GetValues(Suit::typeid)) {
         for each (FaceValue faceValue in Enum::GetValues(FaceValue::typeid)) {
            Card^ card = gcnew Card();
            card->Suit = (Suit) suit;
            card->FaceValue = (FaceValue) faceValue;
            deck[deckCtr] = card;  
            deckCtr++;
         }
      }
      
      for (int ctr = 0; ctr < order->Length; ctr++)
         order[ctr] = rnd->NextDouble();

      Array::Sort(order, deck);
   }

   array<Card^>^ Deal(int numberToDeal)
   {
      if (mustReshuffle) {
         Console::WriteLine("There are no cards left in the deck");
         return nullptr;
      }
      
      array<Card^>^ cardsDealt = gcnew array<Card^>(numberToDeal);
      for (int ctr = 0; ctr < numberToDeal; ctr++) {
         cardsDealt[ctr] = deck[ptr];
         ptr++;
         if (ptr == deck->Length)
            mustReshuffle = true;

         if (mustReshuffle & ctr < numberToDeal - 1) {
            Console::WriteLine("Can only deal the {0} cards remaining on the deck.",
                               ctr + 1);
            return cardsDealt;
         }
      }
      return cardsDealt;
   }
};

void ShowCards(array<Card^>^ cards)
{
   for each (Card^ card in cards)
      if (card != nullptr)
         Console::WriteLine("{0} of {1}", card->FaceValue, card->Suit);
};

void main()
{
   Dealer^ dealer = gcnew Dealer();
   ShowCards(dealer->Deal(20));
}

// The example displays output like the following:
//       Six of Diamonds
//       King of Clubs
//       Eight of Clubs
//       Seven of Clubs
//       Queen of Clubs
//       King of Hearts
//       Three of Spades
//       Ace of Clubs
//       Four of Hearts
//       Three of Diamonds
//       Nine of Diamonds
//       Two of Hearts
//       Ace of Hearts
//       Three of Hearts
//       Four of Spades
//       Eight of Hearts
//       Queen of Diamonds
//       Two of Clubs
//       Four of Diamonds
//       Jack of Hearts
using System;

// A class that represents an individual card in a playing deck.
public class Card
{
   public Suit Suit; 
   public FaceValue FaceValue;
   
   public override String ToString() 
   {
      return String.Format("{0:F} of {1:F}", this.FaceValue, this.Suit);
   }
}

public enum Suit { Hearts, Diamonds, Spades, Clubs };

public enum FaceValue  { Ace = 1, Two, Three, Four, Five, Six,
                         Seven, Eight, Nine, Ten, Jack, Queen,
                         King };

public class Dealer
{
   Random rnd;
   // A deck of cards, without Jokers.
   Card[] deck = new Card[52];
   // Parallel array for sorting cards.
   Double[] order = new Double[52];
   // A pointer to the next card to deal.
   int ptr = 0;
   // A flag to indicate the deck is used.
   bool mustReshuffle = false;
   
   public Dealer()
   {
      rnd = new Random();
      // Initialize the deck.
      int deckCtr = 0;
      foreach (var suit in Enum.GetValues(typeof(Suit))) {
         foreach (var faceValue in Enum.GetValues(typeof(FaceValue))) { 
            Card card = new Card();
            card.Suit = (Suit) suit;
            card.FaceValue = (FaceValue) faceValue;
            deck[deckCtr] = card;  
            deckCtr++;
         }
      }
      
      for (int ctr = 0; ctr < order.Length; ctr++)
         order[ctr] = rnd.NextDouble();   

      Array.Sort(order, deck);
   }

   public Card[] Deal(int numberToDeal)
   {
      if (mustReshuffle) {
         Console.WriteLine("There are no cards left in the deck");
         return null;
      }
      
      Card[] cardsDealt = new Card[numberToDeal];
      for (int ctr = 0; ctr < numberToDeal; ctr++) {
         cardsDealt[ctr] = deck[ptr];
         ptr++;
         if (ptr == deck.Length) 
            mustReshuffle = true;

         if (mustReshuffle & ctr < numberToDeal - 1) {
            Console.WriteLine("Can only deal the {0} cards remaining on the deck.", 
                              ctr + 1);
            return cardsDealt;
         }
      }
      return cardsDealt;
   }
}


public class Example
{
   public static void Main()
   {
      Dealer dealer = new Dealer();
      ShowCards(dealer.Deal(20));
   }
   
   private static void ShowCards(Card[] cards)
   {
      foreach (var card in cards)
         if (card != null)
            Console.WriteLine("{0} of {1}", card.FaceValue, card.Suit);
   }
}
// The example displays output like the following:
//       Six of Diamonds
//       King of Clubs
//       Eight of Clubs
//       Seven of Clubs
//       Queen of Clubs
//       King of Hearts
//       Three of Spades
//       Ace of Clubs
//       Four of Hearts
//       Three of Diamonds
//       Nine of Diamonds
//       Two of Hearts
//       Ace of Hearts
//       Three of Hearts
//       Four of Spades
//       Eight of Hearts
//       Queen of Diamonds
//       Two of Clubs
//       Four of Diamonds
//       Jack of Hearts
' A class that represents an individual card in a playing deck.
Public Class Card
   Public Suit As Suit
   Public FaceValue As FaceValue
   
   Public Overrides Function ToString() As String
      Return String.Format("{0:F} of {1:F}", Me.FaceValue, Me.Suit)
   End Function
End Class

Public Enum Suit As Integer
   Hearts = 0
   Diamonds = 1
   Spades = 2
   Clubs = 3
End Enum

Public Enum FaceValue As Integer
   Ace = 1
   Two = 2
   Three = 3
   Four = 4
   Five = 5
   Six = 6
   Seven = 7
   Eight = 8
   Nine = 9
   Ten = 10
   Jack = 11
   Queen = 12
   King = 13
End Enum

Public Class Dealer
   Dim rnd As Random
   ' A deck of cards, without Jokers.
   Dim deck(51) As Card
   ' Parallel array for sorting cards.
   Dim order(51) As Double
   ' A pointer to the next card to deal.
   Dim ptr As Integer = 0
   ' A flag to indicate the deck is used.
   Dim mustReshuffle As Boolean
   
   Public Sub New()
      rnd = New Random()
      ' Initialize the deck.
      Dim deckCtr As Integer = 0
      For Each Suit In [Enum].GetValues(GetType(Suit))
         For Each faceValue In [Enum].GetValues(GetType(FaceValue))
            Dim card As New Card()
            card.Suit = CType(Suit, Suit)
            card.FaceValue = CType(faceValue, FaceValue)
            deck(deckCtr) = card  
            deckCtr += 1
         Next
      Next
      For ctr As Integer = 0 To order.Length - 1
         order(ctr) = rnd.NextDouble()   
      Next   
      Array.Sort(order, deck)
   End Sub

   Public Function Deal(numberToDeal As Integer) As Card()
      If mustReshuffle Then
         Console.WriteLine("There are no cards left in the deck")
         Return Nothing
      End If
      
      Dim cardsDealt(numberToDeal - 1) As Card
      For ctr As Integer = 0 To numberToDeal - 1
         cardsDealt(ctr) = deck(ptr)
         ptr += 1
         If ptr = deck.Length Then 
            mustReshuffle = True
         End If
         If mustReshuffle And ctr < numberToDeal - 1
            Console.WriteLine("Can only deal the {0} cards remaining on the deck.", 
                              ctr + 1)
            Return cardsDealt
         End If
      Next
      Return cardsDealt
   End Function
End Class

Public Module Example
   Public Sub Main()
      Dim dealer As New Dealer()
      ShowCards(dealer.Deal(20))
   End Sub
   
   Private Sub ShowCards(cards() As Card)
      For Each card In cards
         If card IsNot Nothing Then _
            Console.WriteLine("{0} of {1}", card.FaceValue, card.Suit)
      Next
   End Sub
End Module
' The example displays output like the following:
'       Six of Diamonds
'       King of Clubs
'       Eight of Clubs
'       Seven of Clubs
'       Queen of Clubs
'       King of Hearts
'       Three of Spades
'       Ace of Clubs
'       Four of Hearts
'       Three of Diamonds
'       Nine of Diamonds
'       Two of Hearts
'       Ace of Hearts
'       Three of Hearts
'       Four of Spades
'       Eight of Hearts
'       Queen of Diamonds
'       Two of Clubs
'       Four of Diamonds
'       Jack of Hearts

注意 (継承者)

派生したクラスの最低限の実装では、.NET Framework 1.0 および 1.1 では、Randomをオーバーライドするために必要なSample()乱数を生成するための新しいまたは変更されたアルゴリズムを定義するメソッド。In the .NET Framework 1.0 and 1.1, a minimum implementation of a class derived from Random required overriding the Sample() method to define a new or modified algorithm for generating random numbers. 派生クラスの基本クラスの実装に任せるでした、 Next()Next(Int32)Next(Int32, Int32)NextBytes(Byte[])、およびNextDouble()の派生クラスの実装を呼び出すメソッドをSample()メソッド。The derived class could then rely on the base class implementation of the Next(), Next(Int32), Next(Int32, Int32), NextBytes(Byte[]), and NextDouble() methods to call the derived class implementation of the Sample() method.

.NET Framework 2.0 以降の動作で、 Next()Next(Int32, Int32)、およびNextBytes(Byte[])メソッドがこれらのメソッドの派生クラスの実装を必ずしも呼び出すはありませんができるように変更されて、Sample()メソッド。In the .NET Framework 2.0 and later, the behavior of the Next(), Next(Int32, Int32), and NextBytes(Byte[]) methods have changed so that these methods do not necessarily call the derived class implementation of the Sample() method. 派生するクラスの結果として、 Random .NET Framework 2.0 をターゲットして、後でこれら 3 つのメソッドをオーバーライドする必要がありますもします。As a result, classes derived from Random that target the .NET Framework 2.0 and later should also override these three methods.

注意 (呼び出し元)

乱数ジェネレーターの実装、Randomクラスは、同じままで、.NET Framework のメジャー バージョン間で保証されません。The implementation of the random number generator in the Random class isn't guaranteed to remain the same across major versions of the .NET Framework. その結果、同じシードは、.NET Framework のさまざまなバージョンで同じ擬似乱数シーケンスになりますとは考えないでください。As a result, you shouldn't assume that the same seed will result in the same pseudo-random sequence in different versions of the .NET Framework.

コンストラクター

Random() Random() Random() Random()

時間に応じて決定される既定のシード値を使用し、Random クラスの新しいインスタンスを初期化します。Initializes a new instance of the Random class, using a time-dependent default seed value.

Random(Int32) Random(Int32) Random(Int32) Random(Int32)

指定したシード値を使用して Random クラスの新しいインスタンスを初期化します。Initializes a new instance of the Random class, using the specified seed value.

メソッド

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

指定したオブジェクトが、現在のオブジェクトと等しいかどうかを判断します。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

既定のハッシュ関数として機能します。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

現在のインスタンスの Type を取得します。Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

現在の Object の簡易コピーを作成します。Creates a shallow copy of the current Object.

(Inherited from Object)
Next() Next() Next() Next()

0 以上のランダムな整数を返します。Returns a non-negative random integer.

Next(Int32) Next(Int32) Next(Int32) Next(Int32)

指定した最大値より小さい 0 以上のランダムな整数を返します。Returns a non-negative random integer that is less than the specified maximum.

Next(Int32, Int32) Next(Int32, Int32) Next(Int32, Int32) Next(Int32, Int32)

指定した範囲内のランダムな整数を返します。Returns a random integer that is within a specified range.

NextBytes(Byte[]) NextBytes(Byte[]) NextBytes(Byte[]) NextBytes(Byte[])

指定したバイト配列の要素に乱数を格納します。Fills the elements of a specified array of bytes with random numbers.

NextBytes(Span<Byte>) NextBytes(Span<Byte>) NextBytes(Span<Byte>) NextBytes(Span<Byte>)
NextDouble() NextDouble() NextDouble() NextDouble()

0.0 以上 1.0 未満のランダムな浮動小数点数を返します。Returns a random floating-point number that is greater than or equal to 0.0, and less than 1.0.

Sample() Sample() Sample() Sample()

0.0 と 1.0 の間のランダムな浮動小数点数を返します。Returns a random floating-point number between 0.0 and 1.0.

ToString() ToString() ToString() ToString()

現在のオブジェクトを表す文字列を返します。Returns a string that represents the current object.

(Inherited from Object)

適用対象