【发布时间】:2017-07-03 08:43:19
【问题描述】:
所以作为一项任务,我必须编写一个程序来模拟一次发五张牌,直到发皇家同花顺。它这样做了 10 次,然后取处理皇家同花顺的平均次数。我编写了一个运行良好的程序,但没有考虑到一副牌不会有两张牌的事实,因此处理皇家同花顺的次数超过 200,000。我想我修复了它,但现在我没有得到任何输出,因为程序没有终止。我是不是无意中放了一个无限循环?
import java.util.Random;
public class Problem1Version2 {
public static void main(String[] args) {
// This program simulates the dealing of poker hands and returns the average
// over 10 rounds of how many hands are dealt until a royal straight flush is received.
// Initialize flush to false, which indicates that a royal straight flush has not
// yet been dealt. Set the count variable, i, to 1.
boolean flush = false;
int i = 1;
// Initialize the cards to 0 before any cards are dealt.
int card1 = 0, card2 = 0, card3 = 0, card4 = 0, card5 = 0;
// Initialize the total number of tries across all experiment rounds to 0.
int totalTries = 0;
// Repeat experiment for 10 seeds.
for (int j = 0; j < 10; j++) {
// The round number is the seed.
Random r = new Random(j);
// Deal hands of 5 until a royal straight flush is dealt.
while (flush == false) {
// To simulate the use of one deck, only one of each card can be dealt in a hand.
while (card1 == card2 || card1 == card3 || card1 == card4 || card1 == card5 ||
card2 == card3 || card2 == card4 || card2 == card5 || card3 == card4
|| card3 == card5 || card4 == card5) {
// Cards 1-13 are the hearts, 14-26 the spades, 27-39 the clubs, and 40-52 the diamonds.
card1 = r.nextInt(52) + 1;
card2 = r.nextInt(52) + 1;
card3 = r.nextInt(52) + 1;
card4 = r.nextInt(52) + 1;
card5 = r.nextInt(52) + 1;
}
// Calculate the max and min of the cards.
int max = Math.max(card1, Math.max(card2, Math.max(card3, Math.max(card4, card5))));
int min = Math.min(card1, Math.min(card2, Math.min(card3, Math.min(card4, card5))));
// Check if the hand dealt is a royal straight flush by confirming that
// they span 5 consecutive numbers (this is true if the difference between
// the max and min is 4 since they are all different), and that they all come
// from the same suit (1-13, 14-26, 27-39, or 40-52).
if (max - min == 4) {
if ((1 <= min) && (13 >= max)) {
flush = true;
}
else if ((14 <= min) && (26 >= max)) {
flush = true;
}
else if ((27 <= min) && (39 >= max)) {
flush = true;
}
else if ((40 <= min) && (52 >= max)) {
flush = true;
}
else {
i++;
}
}
else {
i++;
}
}
// Add count from last round to total number of tries over the 10 rounds.
totalTries += i;
// Reset flush to false for the while loop.
flush = false;
}
// Print the average number of required tries.
System.out.println("The average number of hands it took was " + totalTries / 10.0);
}
}
【问题讨论】:
-
调试,调试,再调试一次!
-
我一行一行地走了,一切都按预期进行。我只是从来没有发现它达到皇家同花顺。
-
考虑使用枚举来表示卡片和
List<Card> deck,可以是Collection.shuffle(deck)。这应该会简化您的代码并有助于简化调试。 -
感谢您的提示。不幸的是,我仅限于过去 3 周在课堂上学到的知识,但我相信这会对你有所帮助!