c ++ Do-While,字符串数组中的随机单词不重复
c++ Do-While, Random Words From Array For String With No Repitition
我想要做的是有一个单词数组,然后从数组中为一个字符串分配一个随机单词,但没有字符串可以有相同的单词。我试过这个但是当它运行时,它只会执行一次 do-while 然后继续下一个 do-while 留下重复项。那么我所写的哪一部分是不正确的,我该如何解决呢?
string1 = words[rand()%110];
do{
string2 = words[rand()%110];
}while (string == string1);
do{
string3 = words[rand()%110];
}while (string3 == string1 && string3 == string2);
第一个循环看起来不错。也许你需要在第二个循环中写 ||
而不是 &&
。
PS : 在第一个循环中,是 while (string2 == string1);
而不是 while (string == string1);
??
std::string getWord(std::vector<std::string> & words, size_t & unusedCount)
{
size_t index = rand() % unusedCount;
--unusedCount;
std::swap(words[index], words[unusedCount]);
return words[unusedCount];
}
std::vector<std::string> words;
// fill in words here
// ...
size_t wordsCount = words.size();
std::string string1 = getWord(word, wordsCount);
std::string string2 = getWord(word, wordsCount);
std::string string3 = getWord(word, wordsCount);
我想要做的是有一个单词数组,然后从数组中为一个字符串分配一个随机单词,但没有字符串可以有相同的单词。我试过这个但是当它运行时,它只会执行一次 do-while 然后继续下一个 do-while 留下重复项。那么我所写的哪一部分是不正确的,我该如何解决呢?
string1 = words[rand()%110];
do{
string2 = words[rand()%110];
}while (string == string1);
do{
string3 = words[rand()%110];
}while (string3 == string1 && string3 == string2);
第一个循环看起来不错。也许你需要在第二个循环中写 ||
而不是 &&
。
PS : 在第一个循环中,是 while (string2 == string1);
而不是 while (string == string1);
??
std::string getWord(std::vector<std::string> & words, size_t & unusedCount)
{
size_t index = rand() % unusedCount;
--unusedCount;
std::swap(words[index], words[unusedCount]);
return words[unusedCount];
}
std::vector<std::string> words;
// fill in words here
// ...
size_t wordsCount = words.size();
std::string string1 = getWord(word, wordsCount);
std::string string2 = getWord(word, wordsCount);
std::string string3 = getWord(word, wordsCount);