洗牌一副牌 [英] Shuffling a deck of cards

查看:129
本文介绍了洗牌一副牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做甲板类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,通过包括&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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆