改组2D纸牌阵列 [英] Shuffling 2D array of cards

查看:52
本文介绍了改组2D纸牌阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维的卡片"数组,我需要按行和列对这个数组进行混洗.

I have a 2 dimensional array of "Cards" and i need to shuffle this array in rows and columns.

我的数组是这样的:

private CardType[,] card =
{
    {CardType.Basic, CardType.Basic2, CardType.Basic4 },
    {CardType.Basic, CardType.Basic2, CardType.Basic30 },
    {CardType.Basic, CardType.Basic10, CardType.Basic5 },
    {CardType.Basic, CardType.Basic20, CardType.Basic30 },
};

我需要一种可以按行和列对卡阵列进行混洗的方法.

I need a method to shuffle card array in rows and columns.

推荐答案

使用Fisher-Yates算法:

Using the Fisher-Yates algorithm:

public static void Shuffle<T>(Random random, T[,] array)
{
    int lengthRow = array.GetLength(1);

    for (int i = array.Length - 1; i > 0; i--)
    {
        int i0 = i / lengthRow;
        int i1 = i % lengthRow;

        int j = random.Next(i + 1);
        int j0 = j / lengthRow;
        int j1 = j % lengthRow;

        T temp = array[i0, i1];
        array[i0, i1] = array[j0, j1];
        array[j0, j1] = temp;
    }
}

使用示例:

CardType[,] cards =
{
    { CardType.Basic, CardType.Basic2, CardType.Basic4 },
    { CardType.Basic, CardType.Basic2, CardType.Basic30 },
    { CardType.Basic, CardType.Basic10, CardType.Basic5 },
    { CardType.Basic, CardType.Basic20, CardType.Basic30 },
};

Random rnd = new Random();
Shuffle(rnd, cards);

请注意,您应该尝试重用 rnd ,而不要重新创建它!

Note that you should try to reuse the rnd, and not recreate it!

请注意 array.Length 如何是数组的总 Length X * Y,以及如何从全局索引" i 我们通过将模数除以长度来将其分为 i0 i1 ( x y )行"( lengthRow ).

Note how array.Length is the total Length of the array, X * Y, and how from a "global index" i we split it in a i0, i1 (x, y) by dividing/doing the modulus with the length of a "row" (lengthRow).

这篇关于改组2D纸牌阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆