0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【C#】偏りが少ないランダムな数字を出力するプログラム

Last updated at Posted at 2021-02-19

はじめに

作ったプログラムをテストする際に何かとランダムデータが必要になってくる。
しかし、備え付けのライブラリでランダムデータを作っても偏りが酷くて困ってしまう。
どうにかして偏りが少ないランダムデータを作ることはできないものか…ということで、C#でランダムデータ生成プログラムを作成してみた。

サンプルプログラム

Sample.cs
using System;
using System.IO;

class Sample
{
    public static void GenerateRandomData()
    {
        string DataPath = @"C:\Folder\RandomData.csv";

        Console.WriteLine("データを生成します。");
        FileStream fs = System.IO.File.Create(DataPath);
        fs.Close();

        using (StreamWriter sw = new StreamWriter(DataPath))
        {
            int RoopCount = 0;

            //TickCountで取得した、コンピュータを起動してからの経過時間をミリ秒単位で取得し、ランダムデータ生成のSeed値とする
            int Seed = Environment.TickCount;
            Random rnd = new Random();

            //ランダムデータ生成件数
            int MaxRoop = 100;


            while (true)
            {
                //ループカウントが生成件数の設定値に到達したらループ終了
                if (RoopCount >= MaxRoop)
                {
                    break;
                }

                //普通のランダムクラスのインスタンスを生成
                Random SeedRoopCountRondom1 = new Random();
                //上限値を適当に設定し、数値をひとつ取り出す
                int SeedRoopCount1 = SeedRoopCountRondom1.Next(200);
                //上限値の分だけループ
                for (int i = 0; i < 200; i++)
                {
                    //ランダムクラス「rnd」にSeed値をインクリメントしたものを与えてインスタンス生成
                    //ここでループを繰り返してSeed値を与えることで、よりランダム性のある数値を作ることができる
                    rnd = new Random(Seed++);

                    //普通のランダムクラスから取得した値とループカウントが同じになればループ終了
                    if (i == SeedRoopCount1)
                    {
                        break;
                    }
                }

                //ランダムデータとして取り出したい範囲の値を設定
                int value = rnd.Next(1, 100000);
                //51ミリ秒待つのがポイント(根拠は正直あまりない…)
                //ここで待機時間を入れないとマシンの性能によってはSeed値に規則性が生まれてしまい、ランダムデータが規則的な間隔で出力されるため
                System.Threading.Thread.Sleep(51);
                //csvにデータを書き込みする
                sw.WriteLine(value);

                RoopCount++;
            }

            Console.WriteLine("データ出力完了");
            Console.ReadKey();
        }
    }
}


出力されたcsvのデータを分布図にまとめてみると、こんな感じになる。
Sample
イイ感じではないだろうか?

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?