洗牌一副牌 [英] Shuffling a deck of cards
问题描述
我正在做甲板类C ++程序。它需要有两种方法:一种弹出一个卡掉在甲板的顶部,另一个洗牌。我关心的是后者。
卡重新psented为整数1至52包容$ P $。什么是最快的算法洗牌(假设随机性的好的水平)?
如果你想实现自己洗牌,很简单,但也是功能洗牌算法:的费雪耶茨洗牌。
当然,要洗牌n个元素的数组:
为我从N - 1 DOWNTO 1做 0≤Ĵ≤I J←随机整数 交换[J]和[I]
,C ++标准库中也有这样的事情,实施了您,如<一个href="http://en.cp$p$pference.com/w/cpp/algorithm/random_shuffle"><$c$c>std::random_shuffle$c$c>,通过包括&LT;算法&GT;
头
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.
Cards are represented as integers 1 to 52 inclusive. What is the fastest algorithm to shuffle the deck (assuming a 'good' level of randomness)?
If you wish to implement the shuffle yourself, a very straightforward but also functional shuffling algorithm: 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]
Of course, the C++ standard library also has things like this implemented for you, such as std::random_shuffle
, included via the <algorithm>
header.
这篇关于洗牌一副牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!