fork download
  1. #include <cstdlib>
  2. #include <ctime>
  3. #include <iostream>
  4. #include <vector>
  5.  
  6. // nValues is the number of unique values to generate.
  7. // vals points to an array large enough to hold nValues numbers.
  8. // min is the smallest number in the range to generate numbers for.
  9. // max is the largest number in the range to generate numbers for.
  10. // IMPORTANT: max-min cannot exceed 255.
  11. void generateUniqueRandomValues(unsigned nValues, unsigned* vals, unsigned min, unsigned max)
  12. {
  13. using std::swap;
  14. using std::rand;
  15.  
  16. const unsigned maxElements = 256 ; // some arbitrary value.
  17. unsigned values[maxElements];
  18.  
  19. const unsigned valuesSize = max - min + 1; // the number of elements of the values array which we will use.
  20.  
  21. for (unsigned i = 0; i < valuesSize; ++i) // fill values with numbers from min to max.
  22. values[i] = min + i;
  23.  
  24. for (unsigned i = 0; i < nValues; ++i)
  25. {
  26. const unsigned valuesLeft = valuesSize - i;
  27.  
  28. const unsigned index = rand() % valuesLeft; // pick a random index for an unused value.
  29. vals[i] = values[index]; // store the value in the user-supplied array.
  30.  
  31. swap(values[index], values[valuesLeft-1]); // swap the used value with the last unused value.
  32. }
  33. }
  34.  
  35. int main()
  36. {
  37. using namespace std;
  38.  
  39. srand(time(0));
  40.  
  41. const unsigned nVals = 7;
  42. const unsigned minVal = 1;
  43. const unsigned maxVal = 50;
  44.  
  45. unsigned randValues[nVals];
  46. generateUniqueRandomValues(nVals, randValues, minVal, maxVal);
  47.  
  48.  
  49. for (unsigned i = 0; i < nVals; ++i)
  50. cout << "#" << i+1 << ": " << randValues[i] << '\n' ;
  51. }
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
#1: 18
#2: 28
#3: 15
#4: 2
#5: 17
#6: 8
#7: 35