Saturday, April 7, 2012

Random


#include <cstdlib>

int random(int min, int max, unsigned rolls = 5, float stretch = 2);

//int random(int min, int max, unsigned rolls){
//   unsigned span = max - min + 1;
//   unsigned total = 0;
//   for (unsigned i = 0; i != rolls; ++i)
//      total += rand() % span;
//   return (total + 0.5) / rolls + min;
//}

int random(int min, int max, unsigned rolls, float stretch){
   if (rolls == 0)
      return (min + max + 1.5) / 2;
   if (rolls == 1)
      return rand() % (max - min + 1);

   int result;
   do{
      unsigned span = max - min + 1;
      unsigned stretchedSpan = span * stretch + .5;
      unsigned total = 0;
      for (unsigned i = 0; i != rolls; ++i)
         total += rand() % stretchedSpan;
      result = 1.0 * total / rolls + .5;
      result -= ((stretchedSpan - span) / 2 - 0.5);
      result += min;
   }while(result < min || result > max);
   return result;
}


#include <iostream>

void testRandom(int min = 1, int max = 20, unsigned rolls = 5, float stretch = 1.5, int data = 800, int multiplier = 10000){
   int span = max - min + 1;
   unsigned a[10000];
   if (span > 10000)
      span = 10000;
   for (int i = 0; i != span; ++i)
      a[i] = 0;

   int num = data * multiplier;
   for (int i = 0; i != num; ++i){
      int index = random(min, max, rolls, stretch) - min;
      ++a[index];
   }
   for (int i = min; i != max + 1; ++i){
      if (i < 10)
         std::cout << ' ';
      if (i < 100)
         std::cout << ' ';
      if (i < 1000)
         std::cout << ' ';
      std::cout << i << '|';
      for (int j = 0; j != (a[i-min] + multiplier/2) / multiplier; ++j)
         std::cout << '*';
      std::cout << '\n';
   }
   std::cout << std::endl;
}

int main(){
   testRandom(1, 80, 5, 1.5, 1500);
}

No comments:

Post a Comment