Skip to content

Instantly share code, notes, and snippets.

@RQN
Last active November 11, 2018 16:34
Show Gist options
  • Save RQN/85bc73bc6831b7f90bfe52b87f85b101 to your computer and use it in GitHub Desktop.
Save RQN/85bc73bc6831b7f90bfe52b87f85b101 to your computer and use it in GitHub Desktop.
乱数生成
// using System;
// using System.Security.Cryptography;
public static class Random
{
/// <summary>
/// 指定された最大値より小さい 0 以上のランダムな整数を返します。
/// </summary>
public static int GetRandomNumber(int maxValue = int.MaxValue)
{
if (maxValue == 0) return 0;
if (maxValue < 0)
throw new ArgumentOutOfRangeException(
$"{nameof(maxValue)} は 0 以上である必要があります。");
var b = new byte[4];
var rng = new RNGCryptoServiceProvider();
rng.GetBytes(b);
int num = BitConverter.ToInt32(b, 0);
return Math.Abs(num % maxValue);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment