Reputation: 71
I've seen someone post this same for loop, but my problem is slightly different. Wouldn't the variable temp
be changed on each iteration, so just leaving one character that keeps getting changed? How are the characters stored? Also, how does the loop know that rand()
won't generate the same number for both index1
and index2
? Sorry if this isn't so clear, i'm a bit of a newbie!
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
int main()
{
enum { WORD, HINT, NUM_FIELDS };
const int NUM_WORDS = 3;
const std::string WORDS[NUM_WORDS][NUM_FIELDS] = {
{ "Redfield", "Main Resident Evil character" },
{ "Valentine", "Will you be mine?" },
{ "Jumbled", "These words are..." }
};
srand(static_cast<unsigned int>(time(0)));
int choice = (rand() % NUM_WORDS);
std::string theWord = WORDS[choice][WORD];
std::string theHint = WORDS[choice][HINT];
std::string jumble = theWord;
int length = jumble.size();
for (int i = 0; i < length; ++i) {
int index1 = (rand() % length);
int index2 = (rand() % length);
char temp = jumble[index1];
jumble[index1] = jumble[index2];
jumble[index2] = temp;
}
std::cout << jumble << '\n'; // Why 'jumbled word' instead of just a character?
std::cin.get();
}
Upvotes: 0
Views: 118
Reputation: 309
Wouldn't the variable temp be changed on each iteration, so just leaving one character that keeps getting changed?
It depends. Notice that you're trying to come up with a new random index1
and a new random index2
in each iteration. What happens if your jumble
variable is Redfield
, and index1 = 1
and index2 = 5
? You would be swapping two e
's.
But because in every iteration you're trying to access chars
in a random position of your jumble
string on positions index1
and index2
:
int index1 = (rand() % length);
int index2 = (rand() % length);
The value of those indexes are unpredictable on each iteration. It could happen that you get a 1
and a 5
again.
Nevertheless, remember that you're creating a variable temp
in every iteration, thereby you wouldn't be changing its value, you would be assigning a new variable in each iteration.
How are the characters stored?
I'm not sure what do you mean here, but every char is stored within 1 byte. Therefore, a string would be a sequence of bytes (char). This sequence is a contiguous block of memory. Every time you're accessing jumble[index1]
, you're accessing the char on position index1
within your string jumble
.
If jumble = "Valentine"
and index1 = 1
, then you will be accessing an a
, because your V
is on position 0.
Also, how does the loop know that rand() won't generate the same number for both index1 and index2?
It doesn't. You would have to come up with a strategy to ensure that this doesn't happen. One approach, but not an efficient one, would be:
int index1 = (rand() % length);
int index2 = (rand() % length);
while (index1 == index2) {
index1 = (rand() % length);
index2 = (rand() % length);
}
Upvotes: 1