问题描述
当我需要洗牌的扑克一副扑克牌中的Java / Android的,我用 Collections.shuffle(名单<>清单)
,当然。我曾经一直这样做,其结果似乎是可以接受的。但事实并非如此。
作为本文介绍,有52个! 52张扑克牌甲板上可能唯一的洗牌。这相当于约2 ^ 226。
但 Collections.shuffle(名单<>清单)
使用新的随机()
默认情况下,它使用一个 48位种子,因此只能产生2 ^ 48独特的洗牌 - 这是只有 3.49 * 10 ^!( - 52)
所有可能的洗牌%的
因此,我怎么洗牌,以正确的方式?
我已经开始使用的SecureRandom
,但是这就够了,最后?
名单,其中,卡>卡=新的ArrayList<卡>();
...
SecureRandom的SecureRandom的;
尝试 {
SecureRandom的= SecureRandom.getInstance(SHA1PRNG);
}
赶上(抛出:NoSuchAlgorithmException E){
SecureRandom的=新的SecureRandom();
}
secureRandom.nextBytes(新的字节[20]); //力的SecureRandom为自身的种子
Collections.shuffle(卡,SecureRandom的);
您可能只能拿到2 不同的手从一个特定的起始安排,但有没有,你开始在同样的要求安排各一次。
presumably,甲板结束(扑克手,二十一点等)后,这将是在一个不确定的顺序,而这些重排的任何一项将是合适的。
和,如果你担心的是,你从一个固定安排在每次启动程序启动,只要坚持退出并重新加载它下一次当订单。
在任何情况下,2 仍是一个巨大的可能性号(部分280,000,000,000,000),绰绰有余纸牌游戏,更何况当你来到一个实现,它的限制洗牌,而不是安排。除非你是一个严重的统计学家或密码专家,你有什么应该罚款。
When I need to shuffle a deck of poker cards in Java/Android, I use Collections.shuffle(List<?> list)
, of course. I've ever been doing this and the results seemed acceptable. But they aren't.
As outlined in this paper, there are 52! possible unique shuffles of a 52 card poker deck. That amounts to about 2^226.
But Collections.shuffle(List<?> list)
uses new Random()
by default which uses a 48-bit seed and can therefore only create 2^48 unique shuffles - which is only 3.49*10^(-52)
percent of all possible shuffles!
So how do I shuffle cards the right way?
I've started using SecureRandom
, but is that enough, finally?
List<Card> cards = new ArrayList<Card>();
...
SecureRandom secureRandom;
try {
secureRandom = SecureRandom.getInstance("SHA1PRNG");
}
catch (NoSuchAlgorithmException e) {
secureRandom = new SecureRandom();
}
secureRandom.nextBytes(new byte[20]); // force SecureRandom to seed itself
Collections.shuffle(cards, secureRandom);
You may only be able to get 2 different hands from a specific starting arrangement but there's no requirement that you start at the same arrangement each time.
Presumably, after the deck is finished (poker hands, blackjack and so on), it will be in an indeterminate order, and any one of those rearrangements will be suitable.
And, if you're worried about the fact that you start from a fixed arrangement each time you start your program, just persist the order when exiting and reload it next time.
In any case, 2 is still a huge number of possibilities (some 280,000,000,000,000), more than adequate for a card game, more so when you come to a realisation that it's limiting shuffles rather than arrangements. Unless you're a serious statistician or cryptographer, what you have should be fine.
这篇关于如何真正洗牌一副牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!