确定一张纸牌冲洗牌

时间:2017-04-05 21:52:50

标签: c# .net optimization

在卡片应用程序中,我使用0-51代表5张牌。

诉讼是this.setState({v: ""});
等级为card / 13
只有4种可能的套装(铁锹,心形,俱乐部钻石)

如果所有五件套装都是相同的,则是同花顺。所有冲洗都具有相同的价值。黑桃和钻石一样。

我知道你会说预优化是邪恶的,但我正在进行一些模拟这样做数百万次,这是最昂贵的一步。卡可以是字节,但使用int计算似乎更快。我没有真正检查范围,但我把它放进去,所以你会知道有一个范围。

有更有效的方法吗?

card %

2 个答案:

答案 0 :(得分:2)

我使用位域来存储有关卡的信息,它可能更快,这样就可以避免整数除法和模运算的费用。

csh

为卡片生成值:

const Int32 SuitMask = 0x001100000;
const Int32 Spade    = 0x000000000;
const Int32 Heart    = 0x000100000;
const Int32 Diamond  = 0x001000000;
const Int32 Club     = 0x001100000;

public static Boolean AllCardsInHandOfSameSuit(Int32[] hand) {

    Int32 countSpades   = 0;
    Int32 countHeart    = 0;
    Int32 countDiamonds = 0;
    Int32 countClubs    = 0;

    foreach( Int32 card in hand ) {

        Int32 suit = card & SuitMask;
        switch( suit ) {
            case Spade:
                countSpades++;
                break;
            case Heart:
                countHearts++;
                break;
            case Diamond:
                countDiamonds++;
                break;
            case Club:
                countClubs++;
                break;
        }
    }

    // Your question is not worded clearly about whether or not you care about unique ranks, only unique suits:
    // I'm also unsure of your flush/hand rules, but just compare the counts as-required:
    Boolean allSameSuit = 
        ( countSpades   == 0 || countSpades   == hand.Length ) &&
        ( countHearts   == 0 || countHearts   == hand.Length ) &&
        ( countDiamonds == 0 || countDiamonds == hand.Length ) &&
        ( countClubs    == 0 || countClubs    == hand.Length );

    Boolean allDifferentSuit =
        countSpades   <= 1 &&
        countHearts   <= 1 &&
        countDiamonds <= 1 &&
        countClubs    <= 1;

}

例如:

public static Int32 CreateCard(Int32 suit, Int32 rank) {

    return suit | ( rank & 0x0000 );
}

答案 1 :(得分:2)

消除HashSet应该加快速度:

public static bool IsFlush(int[] hand)
{
    int firstSuit = hand[0] / 13;
    for (int i = 1; i < hand.Length; i++)
    {
        int card = hand[i];
        if (card < 0 || card > 51)
            throw new IndexOutOfRangeException();
        if (firstSuit != (card / 13))
            return false;
    }
    return true;
}

我的(公认的微薄)测试表明性能提升了20%。