简体   繁体   English

如何使用Java随机播放一副纸牌(尝试使用哈希图,不起作用)?

[英]How to shuffle a deck of cards using Java (trying to use hashmap, not working)?

I have a hashmap<Integer, Card> Card is a class. 我有一个hashmap<Integer, Card> Card是一个类。 I have initialized the hashmap with keys from 0-51 and the values are array of Card , as follows 我已经使用0-51的keys初始化了hashmap ,其值是Card数组,如下所示

Card [] card = new Card[52]
for (int i=1; i<=13; i++)
    for (int j=0; j<4; j++)
        card[++index] = new Card( ((i*10)+j) );

and I populate the hashmap as follows: 然后按以下方式填充hashmap

for (int i=1; i<=13; i++)
    for (int j=0; j<4; j++)
        deck.put( ++key, card[++index] );

Now, what I want to do is to shuffle the values side of the hashmap , i do not want,for an example, the key[1] corresponds to card[0] and key[1] corresponds to card[1]. 现在,我想要做的就是shuffle的值侧hashmap ,我不希望,对于一个例子,关键[1]对应于卡[0]和key [1]对应于卡[1]。 I want, for an exampel, the key[1] corresponds to card[38]. 我想,例如,钥匙[1]对应于卡片[38]。 I want the values side to be shuffled. 我希望价值观方面可以改组。 I tried the following: 我尝试了以下方法:

Collections.shuffle(card,new Random()); But it seems it accepts only ArrayList and List . 但似乎它只接受ArrayListList

HashMaps do not have a predictable order, and shuffling an unordered data structure doesn't make sense. HashMaps没有可预测的顺序,并且改组无序的数据结构没有任何意义。 From the Java reference docs: 从Java参考文档:

This class makes no guarantees as to the order of the map; 此类无法保证地图的顺序。 in particular, it does not guarantee that the order will remain constant over time. 特别是,它不能保证顺序会随着时间的推移保持恒定。

If you are using keys from 0-51, you should just add all of the cards to an ArrayList. 如果您使用的是0-51之间的键,则应将所有卡添加到ArrayList中。 Then you can use Collections.shuffle(arrayList) 然后可以使用Collections.shuffle(arrayList)

can I shuffle an array? 我可以改组数组吗?

Yes. 是。 Here's one way. 这是一种方法。

Integer[] t = { 1, 2, 3, 4, 5 };
Collections.shuffle(Arrays.asList(t));
System.out.println(Arrays.toString(t));

You should consider adjusting your design to include a Deck and Card class. 您应该考虑调整您的设计以包括Deck and Card类。 Examples are shown below. 示例如下所示。 Your "encoding" for a card has a potential flaw 10*suit + card will have suit 0 card 13 have the same value as suit 1, card 3. If you want to compare two cards to see which "wins", you should add a method to the Card class that does this. 您对卡的“编码”有潜在的缺陷10 *西服+卡将有西服0卡13与西服1,卡3具有相同的值。如果要比较两张卡以查看哪个“获胜”,则应添加Card类的方法可以执行此操作。

Try this: 尝试这个:

Deck Class 甲板类

package com.example.cards;
import java.util.Arrays;
import java.util.Collections;

public class Deck {
    // Class fields
    // Object fields
    private Integer[] deckOrder;
    private int nextCard;
    private Card[] cards;

    public Deck() {
        deckOrder = new Integer[52];
        cards = new Card[52];
        for (int i=0; i < deckOrder.length; i++) {
            deckOrder[i] = i;
            cards[i] = new Card(i/13,i % 13);
        }
    }

    public void shuffle() {
        Collections.shuffle(Arrays.asList(deckOrder));
        nextCard = 0;
    }

    public Card deal() {
        if (nextCard < deckOrder.length) {
            nextCard++;
            return cards[deckOrder[nextCard-1]];
        } else {
            return null;
        }
    }
}

Card Class 卡类

package com.example.cards;

public class Card {
    // Class fields
    public final static String[] suit = {"Spades","Hearts","Diamonds","Clubs"};
    public final static String[] card = {"Ace","King","Queen","Jack","Ten","Nine"
                                        ,"Eight","Seven","Six","Five","Four"
                                        ,"Three","Two"};
    // Object fields
    private int suitIndex;
    private int cardIndex;

    public Card(int suit, int card) {
        suitIndex = suit;
        cardIndex = card;
    }
    public int getSuitIndex() { return suitIndex;}
    public int getCardIndex() { return cardIndex;}
    public String getSuit() { return suit[suitIndex];}
    public String getCard() { return card[cardIndex];}

    public int getEncodedCard() { return 100*suitIndex + cardIndex;}
}

Test driver 测试驱动

package com.example.cards;
public class TestShuffle {
    public static void main(String[] args) {
        Deck myDeck = new Deck();
        for (int deal = 1; deal < 3; deal++) {
            System.out.println("======================Deal " + deal);
            for (int i = 0; i < 52; i++) {
                Card nextCard = myDeck.deal();
                System.out.println("Card " + i + ". " + nextCard.getCard()
                        + " of " + nextCard.getSuit() + "(encoded "
                        + nextCard.getEncodedCard() + ")");
            }
            myDeck.shuffle();
        }
    }
}

try this: 尝试这个:

public static void main(String args[]) {
    Map<String, Object> x = new HashMap<String, Object>();
    x.put("x", 1); x.put("y", 2); x.put("z", 3); x.put("w", 4);
    System.out.println(x);
    List<Object> vs = new ArrayList<Object>(x.values());
    Collections.shuffle(vs);
    System.out.println(vs);
    Iterator<Object> vIter = vs.iterator();
    for (String k : x.keySet()) x.put(k, vIter.next());
    System.out.println(x);
}

output : 输出:

{w=4, x=1, y=2, z=3}
[2, 3, 1, 4]
{w=2, x=3, y=1, z=4}

What you can do is extract your key value pairs as a List of Map.Entry and shuffle it and put your Map.Entry values in the cleared map 您可以做的是将键值对提取为Map.EntryList ,然后将其洗牌,然后将Map.Entry值放入已清除的地图中

  Set<Map.Entry<Integer,Card> cardEntrySet= deck.entrySet();
    List<Map.Entry<Integer,Card> cardsEntryList = new ArrayList<>(cardEntrySet);
    Collections.shuffle(cardsEntryList);
    deck.clear();

    for(Map.Entry<Integer,Card> entry :cardsEntryList){
      deck.put(entry.getKey(),entry.getValue());
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM