Randomness is a test developer’s best friend.  The following example is a C++ class called CRandomNumbers.  It has two public static methods that generate random numbers.  CRandomNumbers::getRandomNumber() returns a single random number between iMin and iMax and CRandomNumbers::getRandomNumbers() returns a vector of random numbers between iMin and iMax with the total number set as iSize.  The latter leverages the former to generate its numbers.  You can set bUniqueOnlyFlag to true to ensure that all numbers in the vector are unique.

The private CRandomNumbers::initialize() method should be called only once.  It sets the pseudo-random seed using the time() function.  I also rand() to ensure to flush out the first, possibly predicable, number.  I noticed on my system that if I didn’t do this then the first number was always the same.  Finally, I used a map to do number lookups quicker when checking for unique values.

Don’t forget to add some error checking in this code.  You may want to consider using templates as well since then you can support other numeric types like longs and doubles.

// RandomNumbers.h
#pragma once

#include <vector>

using namespace std;

class CRandomNumbers
{

public:

  static int getRandomNumber(
     int iMin, 
     int iMax
     );

  static vector getRandomNumbers(
     int iMin,  
     int iMax, 
     int iSize,  
     bool bUniqueOnlyFlag
     );

protected:

private:

  static void initialize();

};
// RandomNumbers.cpp

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <map>
#include "RandomNumbers.h"

int CRandomNumbers::getRandomNumber
(
   int iMin, 
   int iMax
)
{
  static bool bIsInitialized = false;

  if ( !bIsInitialized )
  {
    initialize();

    bIsInitialized = true;
  }

  return ( iMin + int( (iMax - iMin + 1) * 
             rand() /(RAND_MAX + 1.0) ) );
}

vector CRandomNumbers::getRandomNumbers
(
   int iMin, 
   int iMax, 
   int iSize, 
   bool bUniqueOnlyFlag
)
{
  vector viRandomNumbers;

  viRandomNumbers.clear();

  if ( !bUniqueOnlyFlag ) 
  {
    for ( int i = 0; i < iSize; i++ )
    {
      viRandomNumbers.push_back(getRandomNumber(iMin, iMax));
    }

    return viRandomNumbers;
  }

  map  viUniqueRandomNumbers;

  for ( int i = 0; i < iSize; )
  {
    int iRandomNumber = getRandomNumber(iMin, iMax);

    if ( viUniqueRandomNumbers.find(iRandomNumber) == 
         viUniqueRandomNumbers.end() )
    {
      viRandomNumbers.push_back(iRandomNumber);

      viUniqueRandomNumbers[iRandomNumber] = true;

      ++i;
    }
  }

  return viRandomNumbers;
}

void CRandomNumbers::initialize()
{
  srand((unsigned)time(0));

  rand();

  return;
}
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)