有没有什么算法可以打乱单词?

发布于 2024-12-22 23:43:55 字数 1435 浏览 2 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

丢了幸福的猪 2024-12-29 23:43:55

用于查找元素序列(或者在您的情况下,单词中的字母)的随机排列的标准算法是 Fisher-Yates shuffle,它在线性时间内产生元素序列的真正随机排列。该算法已经很成熟,并且许多标准库都提供了它的实现(例如,C++ std::random_shuffle 算法通常使用此算法实现),因此您也许能够找到预先编写的实现。如果不是,该算法非常容易实现,这里有一些伪代码:

for each index i = 0 to n - 1, inclusive:
    choose a random index j in the range i to n - 1, inclusive.
    swap A[i] and A[j]

实现此算法时要小心,选择随机索引时,您选择 0 到 n-1 之间的索引(包括 0 和 n-1) ;这会产生字母的不均匀分布(您可以阅读更多有关

希望这有帮助!

The standard algorithm for finding a random permutation of a sequence of elements (or, in your case, letters in a word) is the Fisher-Yates shuffle, which in linear time produces a truly random permutation of a sequence of elements. The algorithm is well-established and many standard libraries provide implementations of it (for example, the C++ std::random_shuffle algorithm is typically implemented using this algorithm), so you may be able to find a prewritten implementation. If not, the algorithm is extremely easy to implement, and here's some pseudocode for it:

for each index i = 0 to n - 1, inclusive:
    choose a random index j in the range i to n - 1, inclusive.
    swap A[i] and A[j]

Be careful when implementing this that when picking a random index, you do not pick an index between 0 and n-1 inclusive; this produces a nonuniform distribution of letters (you can read more about that in this earlier question).

Hope this helps!

狠疯拽 2024-12-29 23:43:55

使用Knuth Shuffle(又名 Fisher–Yates Shuffle)。它具有确保集合的每个排列的可能性相同的理想特征。 这里有一个链接,指向 C 语言的实现(以及其他语言的实现),可在任意大小的情况下工作对象。

Go with the Knuth Shuffle (AKA the Fisher–Yates Shuffle). It has the desirable feature of ensuring that every permutation of the set is equally likely. Here's a link to an implementation in C (along with implementations in other languages) that works on arbitrarily sized objects.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文