C++ 洗牌
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4075439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Shuffling a deck of cards
提问by oadams
I'm making a Deck class for a C++ program. It needs to have two methods: one to pop a card off the top of the deck, another to shuffle the deck. I'm concerned with the latter.
我正在为 C++ 程序制作一个 Deck 类。它需要有两种方法:一种是从牌堆顶部弹出一张牌,另一种是洗牌。我关心的是后者。
Cards are represented as integers 1 to 52 inclusive. What is the fastest algorithm to shuffle the deck (assuming a 'good' level of randomness)?
卡片表示为 1 到 52 之间的整数。洗牌的最快算法是什么(假设随机性“良好”)?
回答by Amber
If you wish to implement the shuffle yourself, a very straightforward but also functional shuffling algorithm: Fisher–Yates shuffle.
如果你想自己实现洗牌,一个非常简单但也是功能性的洗牌算法:Fisher–Yates shuffle。
To shuffle an array a of n elements:
for i from n ? 1 downto 1 do j ← random integer with 0 ≤ j ≤ i exchange a[j] and a[i]
对包含 n 个元素的数组 a 进行混洗:
for i from n ? 1 downto 1 do j ← random integer with 0 ≤ j ≤ i exchange a[j] and a[i]
Of course, the C++ standard library also has things like this implemented for you, such as std::random_shuffle
, included via the <algorithm>
header.
当然,C++ 标准库也为您实现了这样的功能,例如std::random_shuffle
通过<algorithm>
头文件包含的。
回答by James McNellis
Use std::random_shuffle
to shuffle the deck.
使用std::random_shuffle
洗牌。
回答by Benjamin Lindley
std::random_shuffle
std::random_shuffle
http://www.cplusplus.com/reference/algorithm/random_shuffle/
http://www.cplusplus.com/reference/algorithm/random_shuffle/