【问题标题】:Sorting a hand of poker整理一手扑克牌
【发布时间】:2015-03-17 18:33:28
【问题描述】:

我正在尝试根据他们的等级和花色对一手扑克牌进行排序,但仍然没有完全排序,这里是代码,注意花色是排序的,但不是等级

排序前我的手:

1:红心之王 2:四颗钻石 3:七支俱乐部 4:俱乐部之王 5:三颗心 6:五颗钻石 7:两个俱乐部 8:钻石之王 9:黑桃四 10:三颗钻石

排序后:

1:黑桃四 2:红心之王 3:三颗心 4:两个俱乐部 5:俱乐部之王 6:七支俱乐部 7:钻石之王 8:五颗钻石 9:四颗钻石 10:三颗钻石

卡片对象

public int compareTo(Card that)
{
    if(this.suit.ordinal() > that.suit.ordinal())
    {
        return 1;
    }
    if(this.suit.ordinal() < that.suit.ordinal()) 
    {
        return -1;
    }       

    int rank1 = (this.rank.ordinal() + 11) % 13; //A>K
    int rank2 = (that.rank.ordinal() + 11) % 13;

    if(rank1 > rank2) return 1;
    if(rank1 < rank2) return -1;
    return 0;
}

玩家对象

public void tryTest()
{
    Card temp = new Card();
    for(int i=0;i<countCard;i++)
    {
        for(int j=0;j<countCard;j++)
        {
            if(playerHand[i].compareTo(playerHand[j]) > 0)
            {
                temp=this.playerHand[j];
                this.playerHand[j] = this.playerHand[i];
                this.playerHand[i] = temp;
            }
        }
    }
}

枚举排名

ACE,
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN,
JACK,
QUEEN,
KING;

枚举套装

DIAMONDS,
CLUBS,
HEARTS,
SPADES;

【问题讨论】:

  • i can sort the hand, but it is still not fully sorted 这是什么意思?
  • 编辑了我的帖子以解释更多@@
  • 你能提供枚举的代码:西装和等级吗?我相信有一个错误。
  • 完成编辑问题

标签: java


【解决方案1】:

查看一些标准的sorting algorithms。您现在拥有的代码将所有内容与其他所有内容进行比较,然后如果其中一个大于另一个则交换它们。但是,这可能会导致您向后交换:

1, 2

2>1 因此交换

2,1

与您所拥有的最接近的算法是冒泡排序,它使用略有不同的索引:

for(int i=0;i<countCard;i++)
{
    for(int j=0;j<countCard -1;j++)
    {
        if(playerHand[j].compareTo(playerHand[j+1]) > 0)
        {
            temp=this.playerHand[j+1];
            this.playerHand[j+1]= this.playerHand[j];
            this.playerHand[j] = temp;
        }
    }
}

【讨论】:

  • 试过这个,结果我的手有重复牌
  • @ロクサスRoxasYap 仔细检查你没有在某处混淆 j 和 j+1
  • 哦,我真傻,我确实搞错了 j 和 j+1,感谢您的帮助,它现在解决了我的问题,谢谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-01
  • 2011-04-19
  • 2015-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多