[英]How do I print out a random, two-dimensional array without duplicates?
我的CompSci類有一個正在做的作業,其中我們必須將一副紙牌打印為二維,6行8列的數組。 每個“卡片”基本上都是隨機產生的數字(1-12)和隨機選擇的衣服(鑽石,紅心,黑桃和棍棒); 陣列中的任何位置都不能重復存儲卡。 這是我的代碼:
static Random random = new Random(1234567);
static int i = 1;
static int a;
static int d;
static List<String> suits = new LinkedList<String>();
static List<String> cards = new LinkedList<String>();
static int[][] grid = new int[6][8];
public static void main(String[]args)
{
suits.add("Diamonds");
suits.add("Clubs");
suits.add("Hearts");
suits.add("Spades");
cards.add("1");
cards.add("2");
cards.add("3");
cards.add("4");
cards.add("5");
cards.add("6");
cards.add("7");
cards.add("8");
cards.add("9");
cards.add("10");
cards.add("11");
cards.add("12");
drawGrid();
}
private static void drawGrid()
{
for(int b = 0; b < grid.length; b++)
{
for(int c = 0; c < grid[i].length; c++)
{
a = (int)(Math.floor(suits.size() * Math.random()));
d = (int)(Math.floor(suits.size() * Math.random()));
System.out.print(" |" + cards.get(d) + " " + suits.get(a) + "|");
Collections.shuffle(suits);
Collections.shuffle(cards);
}
System.out.println();
}
}
有不同的方法可以做到這一點。 我的第一個想法是創建一個整數數組列表。
ArrayList<int[]> list = new ArrayList<int []> ();
for (int i=0; i<suits.size(); i++)
{
for(int j=0; j<cards.size(); j++)
{
int[] card = {i,j};
list.add(card);
}
}
Collections.shuffle(list);
現在,每個元素都代表一張卡片。 使用前6個元素,您將獲得6張隨機卡片。 元素[0] =西裝和元素[1] =卡號
創建一個變量以記住是否已抽簽
static boolean[][] drawn = new boolean[4][13];
然后將您抽出卡片的位置替換為:
do {
a = (int)(Math.floor(suits.size() * Math.random()));
d = (int)(Math.floor(cards.size() * Math.random()));
} while (drawn[a][d]);
drawn[a][d] = true;
最后,刪除要拖曳兩個集合的兩行。 Math.random將為您提供隨機卡。
Collections.shuffle(suits);
Collections.shuffle(cards);
您可以做的是將以前選擇的卡存儲在某個地方,以免重復。 我相信這會有所幫助:
創建一個集合,將其稱為selectedCardMap :
static Set<String> selectedCardMap = new HashSet<String>();
讓我們替換這兩行代碼:
a = (int)(Math.floor(suits.size() * Math.random()));
d = (int)(Math.floor(suits.size() * Math.random()));
對於將為您提供新的未使用卡的方法,請調用此方法getNewCard ,並在內部創建與您嘗試獲取的隨機數相同的隨機數,但是這次,在獲得卡之后,我們檢查是否選擇了卡,是否是的,然后重復並再次檢查,直到得到未選中的對象,如下所示:
public static String getNewCard() {
while (true) {
int a = (int)(Math.floor(suits.size() * Math.random()));
int d = (int)(Math.floor(suits.size() * Math.random()));
//Make a key for the map
String key= d+"-"+a;
//check if it was selected
if (!selectedCardMap.contains(key)) {
//This card is available, add it to selected and return it!
selectedCardMap.add(key);
return " |" + cards.get(d) + " " + suits.get(a) + "|";
}
}
}
此后,繼續您所做的一切!,對不起,如果有任何代碼錯誤,我只是編寫了此代碼而沒有對其進行編譯。 但這是代碼的主要思想。 希望您能理解,對您有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.