根据用户输入生成随机字母

Generate Random Letters Depending on User Input

本文关键字:随机 用户 输入      更新时间:2023-10-16

我必须做一个简单的猜信游戏。到目前为止,我已经完成了几乎所有工作,但是当涉及到一项任务时,我不确定该怎么做。因此,在游戏开始之前,它会要求用户输入两件事:

输入

不同字符的数量:(例如,如果输入 4,则选择的字母将从 A 到第 4 个字母,仅限 A-D)

输入图案长度:

模式长度输入工作正常,但我很难弄清楚如何修改生成代码函数以添加不同字符的数量。

有什么提示吗?

#include <iostream>
#include <random>
#include <string>
using namespace std;
size_t len;
string str;
void generate_code()
{
    str.string::reserve(len);
    random_device rd;
    mt19937 gen{rd()};
    uniform_int_distribution<char> dis{'A', 'Z'};
    for (size_t i = 0; i < len; i++) 
    {
        str += dis(gen);
    }
}
void guess_checker()
{
    string guess{};
    size_t trial_count = 0, match_count = 0;
    do 
    {
        cout << "Enter your guess: " << endl;
        cin >> guess;
        if (guess.size() != len) 
        {
            cout << "error: invalid guess" << endl;
        } 
        else 
        {
            match_count = 0;
            for (size_t i = 0; i < len; i++) 
            {
                if (guess[i] == str[i])
                ++match_count;
            }
            cout << "You guessed " << match_count << " character"
              << (match_count == 1 ? "" : "s") << " correctly." << endl;
        }
        ++trial_count;
   } 
   while (match_count != len);
   cout << "You guessed the pattern in " << trial_count << " guess"
     << (trial_count == 1 ? "" : "es") << "." << endl;
}
int main()
{
    int amount;
    cout << "Enter the amount of different characters: ";
    cin >> amount;
    cout << "Enter the pattern length: ";
    cin >> len;
    generate_code();
    guess_checker();
    return 0;
}

只需将发电机行更改为:

uniform_int_distribution<char> dis{'A', 'A' + amount - 1};

我还建议事先添加一些验证,例如:

if (amount < 1 || amount > 26) {
    cout << "Bad amount" << endl;
    // exit or something
}