【问题标题】:Writing a C++ program to print the letters of a string in a chaotic order编写一个 C++ 程序以乱序打印字符串的字母
【发布时间】:2021-04-12 05:35:06
【问题描述】:

我想要做的是:

  • 用户输入一个字符串(例如:“Hello”)
  • 程序返回相同的字符串,但顺序是随机的(可以是“elHlo”或任何其他可能的顺序)

到目前为止,我已经编写了这段代码,但问题是有时随机生成的数字是相同的,因此它可能会打印两次或更多次相同的索引(字母):

#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;
}

谁能帮我解决它?

【问题讨论】:

    标签: c++ string random


    【解决方案1】:

    您可以使用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;
    }
    

    【讨论】:

      【解决方案2】:

      与调用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';
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多