mercredi 25 mai 2016

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 ?




Aucun commentaire:

Enregistrer un commentaire