如何“洗牌”arrays?

我正在努力创建一个“shuffleDeck()”方法。

我要做的是创建一个方法,它将采用一个数组参数(这将是卡片组)洗牌,并返回洗牌数组列表。

这是代码:

class Card { int value; String suit; String name; public String toString() { return (name + " of " + suit); } } public class PickACard { public static void main( String[] args) { Card[] deck = buildDeck(); // display Deck(deck); int chosen = (int)(Math.random()* deck.length); Card picked = deck[chosen]; System.out.println("You picked a " + picked + " out of the deck."); System.out.println("In Blackjack your card is worth " + picked.value + " points."); } public static Card[] buildDeck() { String[] suits = {"clubs", "diamonds", "hearts", "spades" }; String[] names = {"ZERO", "ONE", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "Jack", "Queen", "King", "Ace" }; int i = 0; Card[] deck = new Card[52]; for ( String s: suits ) { for ( int v = 2; v10) c.value = 10; else c.value = v; deck[i] = c; i++; } } return deck; } public static String[] shuffleDeck( Card[] deck) { /** I have attempted to get two index numbers, and swap them. I tried to figure out how to loop this so it kind of simulates "shuffling". */ } public static void displayDeck( Card[] deck) { for ( Card c: deck) { System.out.println(c.value + "\t" + c); } } } 

怎么样:

 List list = Arrays.asList(deck); Collections.shuffle(list); 

一种方法是将数组转换为列表,并使用java.util.Collections.shuffle(array)来混淆它:

 Card[] deck = ...; List list = Arrays.asList(deck); Collections.shuffle(list); 

如果您仍然需要数组而不是List,则可以添加:

 list.toArray(deck); 

这是一个TIO(Try-it-online)链接,用于查看列出转换和随机播放的数组。

下面复制的TIO代码作为参考:

 import java.util.Arrays; import java.util.Collections; import java.util.List; class M{ public static void main(String[] a){ // Original array Integer[] array = new Integer[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }; System.out.println("before: " + Arrays.toString(array)); // Convert array to list List list = Arrays.asList(array); // And shuffle that list Collections.shuffle(list); System.out.println("after as list: " + list); // (Optional) then convert the list back to an array, // and save it in its initial variable (`array` in this case) list.toArray(array); System.out.println("after as array: " + Arrays.toString(array)); } } 

我认为有两种方法可以做到:

– >如果你想实现自己的方法,你可以使用像Fisher-Yates shuffle算法这样的shuffle算法。

– >您可以使用Collections中的shuffle方法

如果这是一个学校项目(我认为是这样),你可能不允许使用内置函数,如Collections :: shuffle()。 如果是这种情况,那么你必须尝试模拟随机性(在编程中可能会非常困难)。

创建随机感的最常见方式是使用RNG(随机数生成器) 。 如你所说

我试图得到两个索引号,并交换它们。

正确。 洗牌的一种方法是一次挑选一张牌并随机选择另一张牌来交换位置。

  • 你知道牌组总共有52张牌。
  • 您有一个随机生成器来选择随机索引。
  • 你有一个带循环结构的编程语言。

使用这些工具,您可以非常轻松地实现自己的shufflefunction。