【问题标题】:Logic behind generating random upper and lower case letter生成随机大小写字母背后的逻辑
【发布时间】:2016-08-18 23:28:04
【问题描述】:

我正在尝试同时生成一个包含大小写字母的数组。

我确实理解生成两个不同大小写字母的逻辑。

rand() % 26 + 65 // generate all the uppercase letter

同时

rand() % 26 + 97 // generate all the lowercase letter

我尝试在谷歌上搜索如何同时生成它们,这就是我得到的。

rand() % 26 + 65 + rand() % 2 * 32 // generate both upper and lowercase letter

不幸的是,他们没有准确解释其背后的逻辑,我不想盲目地将其复制并粘贴到我的作业中。将第二个rand() 添加到第一个rand() 时,一直在寻找rand() % 2 * 32 背后的逻辑。

我们将不胜感激。

【问题讨论】:

  • 这只是 ASCII 编码的无聊细节。你可以盯着它看一会儿,直到它有意义为止。
  • 首先,您应该避免使用幻数。例如,第一个 sn-p 最好写成rand() % ('Z' - 'A' + 1) + 'A'
  • 首先,请尽量避免magic numbers。如果你指的是字符 A,那么就这么说(如'A')。其次,阅读ASCII table 可能会有所帮助。还应注意,您生成字符(上、下或混合)的方法仅适用于使用ASCII 的系统。其他编码仍然存在,尽管它们很少见。
  • @OliverCharlesworth:在这种情况下,我会说这是错误的建议。该代码密切依赖于 ASCII 编码。这里没有一般性。我认为很难想出一个包含字母 AZ 的编码,但不是其中的 26 个,而是连续序列。
  • 还要注意,不管你是否理解,如果你把它复制到你的作业中,你需要注明出处。

标签: c++ random


【解决方案1】:

观察326597的区别,即大小写字母ASCII码的区别。

现在让我们把rand() % 26 + 65 + rand() % 2 * 32分开:

  • rand() % 26 + 65 生成随机大写字母;
  • rand() % 2 * 32 生成 032,从而在一半的时间内将大写字母转换为对应的小写字母。

重写此表达式的另一种更详细的方法是:

letter = rand() % 26 + 65;
if (rand() % 2) {
  letter += 32;
}

【讨论】:

  • 我想问一下,rand() % 2 * 32 是如何生成032 的。例如,我确实理解 rand() % 26 + 65 背后的原因,因为 ASCII 值 65 被视为“起点”,而 rand() % 26 只是从 65 + 26 开始生成随机 ASCII 字符,但 * 如何在rand() 有效吗?
  • @TeoChuenWeiBryan 阅读有关模运算符 % 的更多信息。
  • @TeoChuenWeiBryan:rand() % 2 生成01。当你将它们乘以32 时,你会得到032
  • 非常感谢您的帮助。我很早以前就学习了模运算符,我几乎完全忘记了% 的基本知识。感谢@JoachimPileborg 的其余部分。 :P
【解决方案2】:

生成随机大写或小写字符的替代解决方案可能是使用例如std::string 在系统上使用的任何本机编码方案中保存大写和小写字符。然后使用例如std::uniform_int_distribution 来自 C++11 pseudo-random generator library

类似的东西

// All letters (exchange the dots for the actual letters)
static std::string const letters = "ABC...XYZabc...xyz";

// Initialize the random-number generation
std::random_device rd;
std::mt19937 gen(rd());

// This distribution will generate a value that will work as
// an index into the `letters` string
std::uniform_int_distribution<> dis(0, letters.size() - 1);

// Generate one random character
char random_character = letters[dis(gen)];

请参阅here 以查看它的“实际效果”。

【讨论】:

  • 这个答案很棒,因为它不假定人们通常关注的字母表。世界上还有其他字母,即使是英文。
【解决方案3】:
const char chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

char ch = chars[rand() % 52];

这适用于所有字符编码,而不仅仅是 ASCII。

【讨论】:

    【解决方案4】:

    只需对所有可能的字符数使用 rand:

    int value = rand() % ('Z' - 'A' + 'z' - 'a');
    unsigned char letter = 'A' + value;
    if (letter > 'Z')
    {
      letter = 'a' + value - ('Z' - 'A');
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 2018-08-11
      相关资源
      最近更新 更多