【问题标题】:How to create a riffle shuffle in java using in-shuffle and out-shuffle如何在 java 中使用 in-shuffle 和 out-shuffle 创建一个 riffle shuffle
【发布时间】:2019-12-20 11:59:35
【问题描述】:

我希望创建一个 riffle shuffle。我需要将我的牌组分成相等的两半(顶部和底部),然后通过将两半中的单张牌交错将两半合并在一起。我已经创建了套牌,但我只是不知道如何将它分成相等的两半。

这是我目前的代码:

class Deck
{
    private static String[] suit = {"\u2660", "\u2666", "\u2663", "\u2764"};
    private static String[] rank = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"};
    private static String[] deck = new String[52];

    // create deck
    static
    {
        for (int i = 0; i < deck.length; i++)
        {
            deck[i] = rank[i % 13] + " of " + suit[i / 13];
        }
    }

    // un-shuffled deck
    static void deck()
    {
        for (int i = 0; i < deck.length; i++)
        {
            deck[i] = rank[i % 13] + " of " + suit[i / 13];
            System.out.println(deck[i]);
        }
    }
}

【问题讨论】:

  • 你至少尝试过什么?
  • 提示:要“拆分”你实际上不需要创建两个单独数组的牌组。只需选择下半场的第一张牌即可。

标签: java shuffle


【解决方案1】:

由于您的牌组由 52 张牌组成,因此您必须将其“拆分”为两副牌,每副 26 张牌。正如 Joachim 所说,您不需要为此创建一个新数组,但可以考虑甲板 1 从甲板 [0] 开始,甲板 2 从甲板 [25] 开始。接下来,您将需要一次又一次地检查这些牌组中的每一个,并保存新洗好的牌组。

static String[] shuffleDeck(String[] unshuffledDeck) {
    // Buffer for deck we want to return
    String[] shuffledDeck = new String[unshuffledDeck.length];
    // We start at index 0 for our first deck (lower half)
    int firstDeckIndex = 0;
    // We start at half of the maximum length of the total deck for our second deck (upper half)
    int secondDeckIndex = unshuffledDeck.length / 2;
    // We start going through the indexes of the new deck which we are going to return
    for(int shuffledDeckIndex = 0; shuffledDeckIndex < shuffledDeck.length; shuffledDeckIndex++) {
        // This is for alternating between the two decks. The modulo operator (%) returns the remainder of a division
        // 0 % 2 == 0 equals to true, 1 % 2 == 0 equals to false, 2 % 2 == 0 equals to true etc. 
        if(shuffledDeckIndex % 2 == 0) {
            // We put the current card of the first deck inside our new shuffledDeck
            shuffledDeck[shuffledDeckIndex] = unshuffledDeck[firstDeckIndex];
            // We advance the index to get the next card of the first deck
            firstDeckIndex++;
        } else {
            // Same as with the first deck
            shuffledDeck[shuffledDeckIndex] = unshuffledDeck[secondDeckIndex];
            secondDeckIndex++;
        }
    }
    // We return the new shuffled deck
    return shuffledDeck;
}

我建议您在掌握了概念本身后尝试自己实现一个新功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-05
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    相关资源
    最近更新 更多