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