[英]Writing a C++ program to print the letters of a string in a chaotic order
我想要做的是:
到目前为止,我已经编写了这段代码,但问题是有时随机生成的数字是相同的,所以它可能会打印相同的索引(字母)两次或更多次:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(){
cout << "Say something: ";
string text;
getline(cin, text);
cout << "\nChaotic text: ";
srand(time(0));
for(unsigned int j=0; j<text.length(); j++){
int randomLetter = rand()%text.length();
cout << text.at(randomLetter);
}
return 0;
}
任何人都可以帮我解决它吗?
您可以使用std::shuffle
(C++11 起):
#include <iostream>
#include <string>
#include <random>
#include <algorithm>
using namespace std;
int main(){
cout << "Say something: ";
string text;
getline(cin, text);
cout << "\nChaotic text: ";
std::mt19937 g(time(0));
std::shuffle(text.begin(), text.end(), g);
cout << text;
return 0;
}
或std::random_shuffle
(如果您使用旧规范):
#include <iostream>
#include <string>
#include <cstdlib>
#include <algorithm>
using namespace std;
int main(){
cout << "Say something: ";
string text;
getline(cin, text);
cout << "\nChaotic text: ";
srand(time(0));
std::random_shuffle(text.begin(), text.end());
cout << text;
return 0;
}
您可以在保持跟踪哈希表中所有生成的索引的同时继续生成一个新索引,而不是一次调用rand()
,这可以生成您之前调用过的索引。
std::unordered_map<int, bool> done;
for (unsigned int j = 0; j < text.length(); j++) {
int randomLetter = rand() % text.length();
while (done[randomLetter] == true) // while it's been marked as finished, generate a new index.
randomLetter = rand() % text.length();
cout << text.at(randomLetter);
done[randomLetter] = true; // mark it as finished.
}
或者,您可以改用std::random_shuffle
,这样可以省去麻烦。
std::random_shuffle (text.begin(), text.end());
std::cout << text << '\n';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.