1

I am trying to create a method that generates a random number from a specific selection of numbers, it must be either 0, 90, 180 or 270.

This is the method I have so far to generate a random number between a certain range, but I am not sure how to generate a random number from a specific selection.

int randomNum(int min, int max) {
    return rand() % max + min;
}
genpfault
  • 51,148
  • 11
  • 85
  • 139
Jennifer
  • 115
  • 9

1 Answers1

2

Umm, So as I think you're trying to choose a specific number in a array or so called a list of options, I've a quick example for you here. You can just create a array with all your options and make this method to return a value from the given array.

#include <iostream>
#include <stdlib.h>
#include <time.h>

int main ()
{
  srand ( time(NULL) ); //initialize the random seed
  

  const char arrayNum[4] = {'1', '3', '7', '9'};
  int RandIndex = rand() % 4; //generates a random number between 0 and 3
  cout << arrayNum[RandIndex];
}

More details - http://www.cplusplus.com/forum/beginner/26611/

daysling
  • 118
  • 10
  • For the specific list, {0, 90, 180 or 270}, then `(rand%4)*90)` would probably be a more efficient solution. For the general case, your "lookup table" idea is good. – paulsm4 Aug 16 '21 at 05:09
  • 1
    https://stackoverflow.com/questions/10984974/why-do-people-say-there-is-modulo-bias-when-using-a-random-number-generator https://stackoverflow.com/questions/49880304/random-integers-in-c-how-bad-is-randn-compared-to-integer-arithmetic-what-a https://stackoverflow.com/questions/2560980/looking-for-a-clear-and-concise-web-page-explaining-why-lower-bits-of-random-numb And note that the C++ standard has facilities to sample from an integer range without those defects. See https://stackoverflow.com/questions/288739/generate-random-numbers-uniformly-over-an-entire-range –  Aug 16 '21 at 05:14