0

I am new to cpp programing, and new to stackoverflow.

I have a simple situation and a problem that is taking more time than reasonable to solve, so I thought I'd ask it here.

I want to take one digit from a rand() at a time. I have managed to strip of the digit, but I can't convert it to an int which I need because it's used as an array index.

Can anyone help? I'd be appreciative.

Also if anyone has a good solution to get evenly-distributed-in-base-10 random numbers, I'd like that too... of course with a rand max that isn't all 9s we don't have that.

KTM

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • 2
    Are you willing to break out C++11? It let's you generate arbitrary ranges using `std::uniform_int_distribution`. – tabstop Jan 18 '14 at 22:36

3 Answers3

3

Well you can use the modulus operator to get the digit of what number rand returns.

int digit = rand()%10;

As for your first question, if you have a character digit you can subtract the value of '0' to get the digit.

int digit = char_digit - '0';
Bartlomiej Lewandowski
  • 10,771
  • 14
  • 44
  • 75
  • 2
    This solution assumes that you are willing to accept some (small) bias: http://ericlippert.com/2013/12/16/how-much-bias-is-introduced-by-the-remainder-technique/ – Pete Baughman Jan 18 '14 at 22:40
3

If one wants a pedantic even distribution of 0 to 9 one could

  1. Assume rand() itself is evenly distributed. (Not always a good assumption.)

  2. Call rand() again as needed.

    int ran10(void) {
      const static int r10max = RAND_MAX - (RAND_MAX % 10);
      int r;
      while ((r = rand()) >= r10max);
      return r%10;
    }
    

Example:
If RAMD_MAX was 32767, r10max would have the value of 32760. Any rand value in the range 32760 to 32767 would get tossed and a new random value would be fetched.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

While not as fast as modulo-arithmetic implementations like rand() % 10, this will return evenly distributed integers and avoid perodicity in the least significant bits that occur in some pseudo-random number generators (see http://www.gnu.org/software/gsl/manual/html_node/Other-random-number-generators.html).

int rand_integer(int exclusive_upperbound)
{
        return int((double)exclusive_upperbound*rand()/RAND_MAX);
}
ericman314
  • 41
  • 3