Задача: Простой генератор случайных чисел
Исходник: RandomGenerator.cpp, язык: C++ [code #50, hits: 11793]
автор: this [добавлен: 18.02.2006]
  1. #include "RandomGenerator.h"
  2.  
  3. RandomGenerator::RandomGenerator(int size) {
  4. this->n = size;
  5. this->x = new int[ this->n ];
  6. }
  7.  
  8. // Получает массив из n случайных чисел от left до right
  9. int* RandomGenerator::GetRandom(int left, int right) {
  10.  
  11. for (int i = 0; i < this->n; i++) {
  12. this->x[i] = this->GetOneRandom(left, right);
  13. }
  14. return this->x;
  15. }
  16.  
  17.  
  18. // Получение 1-го случайного числа от left до right
  19. int RandomGenerator::GetOneRandom(int left, int right) {
  20. return (left + rand() % (right - left));
  21. }
  22.  
  23. /* Получение частично-отсортированной последовательности
  24. * Которая будет состоять из чередующихся между собой отрезков
  25. * сортированных последовательностей длинной sortedLength элементов
  26. * и неотсортированных, случайных последовательностей числей,
  27. * длинной unsortedLength элементов
  28. */
  29. int* RandomGenerator::GetPartSorted(unsigned int unsortedLength, unsigned int sortedLength) {
  30. bool sorted = true;
  31. int numerator = 20;
  32. int intervalLength = 0;
  33. for (int i = 0; i < this->n; i++) {
  34. if (sorted) {
  35.  
  36. numerator += 2;
  37. this->x[i] = numerator;
  38. if (++intervalLength == sortedLength) {
  39. sorted = false;
  40. intervalLength = 0;
  41. }
  42. } else {
  43. this->x[i] = this->GetOneRandom(0, this->n);
  44. numerator = this->x[i];
  45.  
  46. if (++intervalLength == unsortedLength) {
  47. sorted = true;
  48. intervalLength = 0;
  49. }
  50. }
  51. }
  52.  
  53. return this->x;
  54. }
  55.  
  56.  
  57.  
  58. int RandomGenerator::getSize(void) {
  59. return this->n;
  60. }
  61.  
  62. RandomGenerator::~RandomGenerator(void) {
  63. delete [] this->x;
  64. }
  65.  
RandomGenerator.cpp :: Реализация класса генератора случайных массивов

Заголовочный файл: RandomGenerator.h
Генерирует массив случайных чисел в 2-х режимах: случайная последовательность и частично отсортированная последовательность случайных чисел.

Тестировалось на: MS Visual Studio 2005, .NET Framework 2.0

+добавить реализацию