我正在为一副牌写一个代码,它会洗牌一副牌。我测试了代码,但我真的不知道它是否真的在做它应该正确做的事情?你怎么看?
这是 shuffle 方法的代码:
public void shuffle()
{
for( int x = myDeck.size(); x > 0 ; x--)
{
Random rn = new Random();
int index1 = rn.nextInt(52);
Card c = myDeck.remove(index1);
myDeck.add(c);
}
}
我的输出似乎在数字上打乱了,但不是像黑桃心等卡片的名字,
例如,这是我测试代码时的输出:
Deuce of spades
Seven of spades
Eight of spades
Ace of spades
Three of hearts
Five of hearts
Six of hearts
Seven of hearts
Nine of hearts
Ten of hearts
Queen of hearts
King of hearts
Ace of hearts
Seven of diamonds
Eight of diamonds
Jack of diamonds
King of diamonds
Three of clubs
Seven of clubs
Nine of clubs
Jack of clubs
Queen of clubs
King of clubs
Ace of clubs
Queen of spades
Deuce of clubs
Three of spades
Nine of diamonds
Four of spades
Four of clubs
Deuce of hearts
Jack of spades
Ten of clubs
Six of diamonds
Jack of hearts
Six of clubs
Four of diamonds
Five of diamonds
Ace of diamonds
Four of hearts
Nine of spades
Ten of spades
Five of spades
Three of diamonds
Six of spades
Five of clubs
Deuce of diamonds
Eight of hearts
King of spades
Ten of diamonds
Eight of clubs
Queen of diamonds
就像总是有重复的名字一样。这是错误的,因为洗牌的目的是把它混合起来吗?
这是一个实际的问题:在打牌时,洗牌当然很重要,也就是说,要安排好东西,以便以随机顺序发牌。有几种方法可以实现这一点。一种策略是反复从牌组中随机挑选一张牌并将其移到最后。以下代码使用 Random 类(您在在线课程的“ArrayLists”部分的第 8 页遇到过)来执行这样的“选择并移动到末尾”操作:
Random rn = new Random();
int index1 = rn.nextInt( 52 );
Card c = myDeck.remove( index1 );
myDeck.add( c );
为了有效地洗牌,这个操作应该重复很多次(比如 500 次)。为使用单个 Random 对象和 for 循环对 myDeck 进行随机播放的 Deck 类创建一个新的实例方法 shuffle。在适当地修改 main 方法后,用它来测试你的新代码。
所以我的主要问题是:我做错了吗?