Генератор случайных чисел генерирует одинаковые числа - C#

Узнай цену своей работы

Формулировка задачи:

Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Threading;
  7. class Rndthread
  8. {
  9. private int RowsA; private int RowsB;
  10. private int ColumsA; private int ColumsB;
  11. private double[,] MatrixA; private double[,] MatrixB;
  12. private int howMuchFlows;
  13. private int NumberOfthread;
  14. static Random WhataNumber = new Random();
  15. Thread RNDThread;
  16. public Rndthread(int name/*имя потока*/, double[,] InputmatrixA/*имя матрицы*/, double[,] InputmatrixB, int m, int n, int k, int amountflow)
  17. {
  18. RowsA = m; RowsB = n;
  19. ColumsA = n; ColumsB = k;
  20. MatrixA = InputmatrixA;
  21. MatrixB = InputmatrixB;
  22. howMuchFlows = amountflow;
  23. NumberOfthread = name;
  24. RNDThread = new Thread(rndfunction);
  25. RNDThread.Priority = ThreadPriority.Highest;
  26. RNDThread.Start();
  27. }
  28. void rndfunction()
  29. {
  30. double[,] mIndex = MatrixA;
  31. int StartColculation = RowsA / howMuchFlows * (NumberOfthread);
  32. int EndColculation = RowsA / howMuchFlows * (NumberOfthread + 1) - 1;
  33. Console.ForegroundColor = ConsoleColor.DarkCyan;
  34. Console.WriteLine("Матрица А - Поток №{0} ведет расчет от {1} строки до {2} строки и имеет в расположении {3} столбцов....", NumberOfthread + 1, StartColculation, EndColculation, ColumsA);
  35. Thread.Sleep(0);
  36. for (int i = StartColculation; i <= EndColculation; i++)
  37. {
  38. for (int j = 0; j < ColumsA; j++)
  39. {
  40. mIndex[i, j] = WhataNumber.Next(-10, 11);
  41. Thread.Sleep(0);
  42. }
  43. }
  44. mIndex = MatrixB;
  45. StartColculation = RowsB / howMuchFlows * (NumberOfthread);
  46. EndColculation = RowsB / howMuchFlows * (NumberOfthread + 1) - 1;
  47. Console.ForegroundColor = ConsoleColor.DarkGray;
  48. Console.WriteLine("Матрица В - Поток №{0} ведет расчет от {1} строки до {2} строки и имеет в расположении {3} столбцов....", NumberOfthread + 1, StartColculation, EndColculation, ColumsB);
  49. Thread.Sleep(0);
  50. for (int i = StartColculation; i <= EndColculation; i++)
  51. {
  52. for (int j = 0; j < ColumsB; j++)
  53. {
  54. mIndex[i, j] = WhataNumber.Next(-10, 11);
  55. Thread.Sleep(0);
  56. }
  57. }
  58. Console.ForegroundColor = ConsoleColor.Red;
  59. Console.WriteLine("Поток №{0} завершил заполнение матрицы случайными числами", NumberOfthread + 1);
  60. }
  61. }
При данном коде возникает вот такая картина:

Решение задачи: «Генератор случайных чисел генерирует одинаковые числа»

textual
Листинг программы
  1. using System;
  2. using System.Security.Cryptography;
  3.  
  4. // Cryptographically-strong random number generator
  5. // Source: MSDN Magazine > 2007 > September > .NET Matters: Tales from the CryptoRandom
  6. // Source URL: [url]http://msdn.microsoft.com/en-us/magazine/cc163367.aspx[/url]
  7. // via [url]https://gist.github.com/prettycode/5471944[/url]
  8. // Authors: Stephen Toub & Shawn Farkas
  9. public sealed class CryptoRandom : Random, IDisposable
  10. {
  11.     private RNGCryptoServiceProvider cryptoProvider = new RNGCryptoServiceProvider();
  12.     private byte[] uint32Buffer = new byte[sizeof(uint)];
  13.  
  14.     /// <summary>
  15.     /// An implementation of System.Random used for cryptographically-strong random number generation.
  16.     /// </summary>
  17.     public CryptoRandom() { }
  18.  
  19.     /// <summary>
  20.     /// An implementation of System.Random used for cryptographically-strong random number generation.
  21.     /// </summary>
  22.     public CryptoRandom(int seedIgnored) { }
  23.  
  24.     /// <summary>
  25.     /// Returns a nonnegative random number.
  26.     /// </summary>
  27.     /// <returns>
  28.     /// A 32-bit signed integer greater than or equal to zero and less than <see cref="F:System.Int32.MaxValue"/>.
  29.     /// </returns>
  30.     public override int Next()
  31.     {
  32.         cryptoProvider.GetBytes(uint32Buffer);
  33.         return BitConverter.ToInt32(uint32Buffer, 0) & 0x7FFFFFFF;
  34.     }
  35.  
  36.     /// <summary>
  37.     /// Returns a nonnegative random number less than the specified maximum.
  38.     /// </summary>
  39.     /// <returns>
  40.     /// A 32-bit signed integer greater than or equal to zero, and less than <paramref name="maxValue"/>; that is, the range of return values ordinarily includes zero but not <paramref name="maxValue"/>. However, if <paramref name="maxValue"/> equals zero, <paramref name="maxValue"/> is returned.
  41.     /// </returns>
  42.     /// <param name="maxValue">The exclusive upper bound of the random number to be generated. <paramref name="maxValue"/> must be greater than or equal to zero.</param>
  43.     /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="maxValue"/> is less than zero.</exception>
  44.     public override int Next(int maxValue)
  45.     {
  46.         if (maxValue < 0) throw new ArgumentOutOfRangeException("maxValue");
  47.         return Next(0, maxValue);
  48.     }
  49.  
  50.     /// <summary>
  51.     /// Returns a random number within a specified range.
  52.     /// </summary>
  53.     /// <returns>
  54.     /// A 32-bit signed integer greater than or equal to <paramref name="minValue"/> and less than <paramref name="maxValue"/>; that is, the range of return values includes <paramref name="minValue"/> but not <paramref name="maxValue"/>. If <paramref name="minValue"/> equals <paramref name="maxValue"/>, <paramref name="minValue"/> is returned.
  55.     /// </returns>
  56.     /// <param name="minValue">The inclusive lower bound of the random number returned.</param>
  57.     /// <param name="maxValue">The exclusive upper bound of the random number returned. <paramref name="maxValue"/> must be greater than or equal to <paramref name="minValue"/>.</param>
  58.     /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="minValue"/> is greater than <paramref name="maxValue"/>.</exception>
  59.     public override int Next(int minValue, int maxValue)
  60.     {
  61.         if (minValue > maxValue) throw new ArgumentOutOfRangeException("minValue");
  62.         if (minValue == maxValue) return minValue;
  63.  
  64.         long diff = maxValue - minValue;
  65.         long max = (1 + (long)uint.MaxValue);
  66.         long remainder = max % diff;
  67.  
  68.         while (true)
  69.         {
  70.             cryptoProvider.GetBytes(uint32Buffer);
  71.             uint rand = BitConverter.ToUInt32(uint32Buffer, 0);
  72.             if (rand < max - remainder)
  73.             {
  74.                 return (int)(minValue + (rand % diff));
  75.             }
  76.         }
  77.     }
  78.  
  79.     /// <summary>
  80.     /// Returns a random number between 0.0 and 1.0.
  81.     /// </summary>
  82.     /// <returns>
  83.     /// A double-precision floating point number greater than or equal to 0.0, and less than 1.0.
  84.     /// </returns>
  85.     public override double NextDouble()
  86.     {
  87.         cryptoProvider.GetBytes(uint32Buffer);
  88.         uint rand = BitConverter.ToUInt32(uint32Buffer, 0);
  89.         return rand / (1.0 + uint.MaxValue);
  90.     }
  91.  
  92.     /// <summary>
  93.     /// Fills the elements of a specified array of bytes with random numbers.
  94.     /// </summary>
  95.     /// <param name="buffer">An array of bytes to contain random numbers.</param>
  96.     /// <exception cref="T:System.ArgumentNullException"><paramref name="buffer"/> is null.
  97.     public override void NextBytes(byte[] buffer)
  98.     {
  99.         if (buffer == null) throw new ArgumentNullException("buffer");
  100.         cryptoProvider.GetBytes(buffer);
  101.     }
  102.  
  103.     public void Dispose()
  104.     {
  105.         InternalDispose();
  106.     }
  107.  
  108.     ~CryptoRandom()
  109.     {
  110.         InternalDispose();
  111.     }
  112.  
  113.     void InternalDispose()
  114.     {
  115.         if (cryptoProvider != null)
  116.         {
  117.             cryptoProvider.Dispose();
  118.             cryptoProvider = null;
  119.         }
  120.     }
  121. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

8   голосов , оценка 4.375 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы