有26个字符,长度最多为n。所以字符串的总数是:
Total Number of Strings = \sum_{i=1}^n 26^i
我们需要以相等的概率选择其中的每一个,即:
P(string s is chosen) = 1 / TotalNumStrings
现在考虑您提出的选择随机长度然后选择该长度的随机字符串的策略。所以根据贝叶斯规则,我们有:
P(string s being chosen which has length i) =
P(string s being chosen | string has length i) *
P(we want a string of length i) = (1 / 26^i) * (1 / n) = 1 / (26^i * n)
不等于 1 / TotalNumStrings。您已经知道这行不通,但这会激发正确的选择策略。
现在选择字符串如下:
P(string s being chosen which has length i) =
P(string s being chosen | string has length i) *
P(we want a string of length i) =
1 / (26^i) * P(chosen string has length i) = 1 / NumStrings.
因此我们有 P(chosen string has length i) = 26^i / NumStrings!多田。
所以总结选择策略如下。首先选择长度 i,概率为 26^i / NumStrings。然后在该类别中选择一个任意字符串。