Random.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //
  2. // System.Random.cs
  3. //
  4. // Author:
  5. // Bob Smith ([email protected])
  6. //
  7. // (C) 2001 Bob Smith. http://www.thestuff.net
  8. //
  9. using System;
  10. namespace System
  11. {
  12. public class Random
  13. {
  14. private int S = 1;
  15. private const int A = 16807;
  16. private const int M = 2147483647;
  17. private const int Q = 127773;
  18. private const int R = 2836;
  19. public Random()
  20. {
  21. S = (int)(DateTime.Now.Ticks);
  22. }
  23. public Random(int Seed)
  24. {
  25. S = Seed;
  26. }
  27. public virtual int Next()
  28. {
  29. return (int)(this.Sample()*Int32.MaxValue);
  30. }
  31. public virtual int Next(int maxValue)
  32. {
  33. if (maxValue < 0)
  34. throw new ArgumentOutOfRangeException("Max value is less then min value.");
  35. else if (maxValue == 0)
  36. return 0;
  37. return (int)(this.Sample()*maxValue);
  38. }
  39. public virtual int Next(int minValue, int maxValue)
  40. {
  41. if (minValue > maxValue)
  42. throw new ArgumentOutOfRangeException("Min value is greater then max value.");
  43. else if (minValue == maxValue)
  44. return minValue;
  45. return (int)(this.Sample()*maxValue)+minValue;
  46. }
  47. public virtual void NextBytes(byte[] buffer)
  48. {
  49. int i, l;
  50. if (buffer == null)
  51. throw new ArgumentNullException();
  52. l = buffer.GetUpperBound(0);
  53. for (i = buffer.GetLowerBound(0); i < l; i++)
  54. {
  55. buffer[i] = (byte)(this.Sample()*Byte.MaxValue);
  56. }
  57. }
  58. public virtual double NextDouble()
  59. {
  60. return this.Sample();
  61. }
  62. protected virtual double Sample(){
  63. S=A*(S%Q)-R*(S/Q);
  64. if(S<0) S+=M;
  65. return S/(double)Int32.MaxValue;
  66. }
  67. }
  68. }