C#でRandomizeの処理をするコードを紹介します。
C#では、Randomクラスを利用して乱数を生成する際に、Randomクラスのコンストラクタを引数なしで作成した場合、
システム クロックを利用してシードが生成されるため、Randomizeの処理が入った状態で乱数を生成できます。
Randomクラスによる乱数の生成の詳細はこちらの記事を参照してください。
Windows Formアプリケーションを作成し以下のコードを記述します。
下図のフォームを作成します。テキストボックスとボタンを配置します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RandomNumberGenerate
{
public partial class FormRandom : Form
{
private Random rnd;
public FormRandom()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int random_num = rnd.Next();
textBox1.Text += string.Format("生成された乱数: {0:d}\r\n", random_num);
}
private void FormRandom_Load(object sender, EventArgs e)
{
rnd = new Random();
}
}
}
プロジェクトを実行します。下図のウィンドウが表示されます。
[button1]ボタンをクリックします。乱数が生成されテキストボックスに表示されます。
ボタンをクリックするごとに乱数が生成されます。
アプリケーションを一度終了し、再度アプリケーションを実行して[button1]をクリックします。
先ほどとは別の乱数が表示されます。
決められた順序での乱数を生成する場合には、Randomクラスのコンストラクタに固定のシード値を与えます。
下図のフォームを作成します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RandomNumberGenerate
{
public partial class FormRandomFixSeed : Form
{
private Random rnd;
public FormRandomFixSeed()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int random_num = rnd.Next();
textBox1.Text += string.Format("生成された乱数: {0:d}\r\n", random_num);
}
private void FormRandomFixSeed_Load(object sender, EventArgs e)
{
rnd = new Random(1);
}
}
}
Randomクラスのコンストラクタにシードの数値を固定値で設定します。
シードを固定値で設定すると、乱数は毎回同じ乱数が生成されます。
今回は "1" を与えています。
private void FormRandomFixSeed_Load(object sender, EventArgs e)
{
rnd = new Random(1);
}
プロジェクトを実行します。下図のウィンドウが表示されます。
[button1]ボタンをクリックします。乱数が生成されテキストボックスに表示されます。
ボタンをクリックするごとに乱数が生成されます。
アプリケーションを一度終了し、再度アプリケーションを実行して[button1]をクリックします。
先ほどと同じ数値が表示されます。