Jimmy Robitaille
Jimmy Robitaille

Reputation: 85

About random numbers in C++

I am really new to C++. I am following a free online course, and one thing I had to do was to create a program which could scramble the characters of a string.

So, I created a function who received the word as parameter and returned the scrambled word. ctime and cstdlib were included and srand(time(0)); declared in the main.

Basically, the function looked like this :

std::string mixingWord(std::string baseWord)
{
std::string mixWord;
int pos(0);

for (int i = baseWord.length; i >= 0; i--)
{
  if (i != 0)
  {
    pos = rand() % i;
    mixWord += baseWord[pos];
    baseWord.erase(pos,1);
  }
  else
  {
    mixWord += baseWord[0];
  }
}

return mixWord;
}

And it worked just fine. But the correct solution was

std::string mixingWord(std::string baseWord)
{
std::string mixWord;
int pos(0);

while (baseWord.size() != 0)
{
    pos = rand() % baseWord.size();
    mixWord += baseWord[pos];
    baseWord.erase(pos, 1);
}

return mixWord;
}

And it works fine as well. My question is : Why is the solution working ? From what I understood, this :

rand() % value

gives out a value between 0 and the value given.

SO, since baseWord.size() returns, let's say 5 in the event of a word like HELLO. rand will generate a number between 0 and 5. So it COULD be 5. and baseWord[5] is out of bound, so it should crash once in a while, but I tried it over 9000 times (sorry, dbz reference), and it never crashed.

Am I just unlucky, or am I not understanding something ?

Upvotes: 1

Views: 99

Answers (3)

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

x % y gives the remainder of x / y. The result can never be y, because if it was, then that would mean y could go into x one more time, and the remainder would actually be zero, because y divides x evenly. So to answer your question:

Am I just unlucky, or am I not understanding something ?

You're misunderstanding something. rand() % value gives a result in the range [0,value - 1] (assuming value is positive), not [0, value].

Upvotes: 6

Garmastewira
Garmastewira

Reputation: 39

I guess you just misunderstood the modulo operator. a % b, with a and b any integer, will return values between 0 and b-1 (inclusive).

As for your HELLO example, it will only return values between 0 and 4, therefore will never encounter out of bound error.

Upvotes: 1

Sagar Patel
Sagar Patel

Reputation: 61

rand() % 100 returns number between 0 and 99. This is 100 NUMBERs but includes 0 and does not include 100.

A good way to think about this is a random number (1000) % 100 = 0. If I mod a random number with the number N then there is no way to get the number N back.

Along those lines pos = rand() % baseWord.size(); will never return pos = baseWord.size() so in your case there will not be an indexing issue

Upvotes: 3

Related Questions