我试图制作一个实现纸牌游戏的程序。但是,对牌组(牌组)进行排序会产生意外的输出。
我的Card.swift
文件具有以下比较功能,首先按以下方式排序:
// For Comparable
public func <(left: Card, right: Card) -> Bool {
if left.suit < right.suit {
return true
}
return left.rank < right.rank
}
每个Card
都有一个Rank
和一个Suit
(在Rank.swift
和Suit.swift
中定义),它们是Int
枚举,其中包含以下内容比较运算符:
public func <(left: Rank, right: Rank) -> Bool {
return left.rawValue < right.rawValue
}
当我制作一个Euchre牌组时:
func makeEuchreDeck() {
for suit in 1...4 {
for rank in 9...14 {
deck.append(Card.init(r: rank, s: suit))
}
}
}
然后对它进行排序(通过deck.sortInPlace()
),它会给出以下输出(使用Rank和Suit的原始值):
9 of 1
9 of 2
9 of 3
9 of 4
10 of 1 //inconsistency here
11 of 1 //something about Clubs makes it act up
12 of 1
10 of 2 //it acts normally except for Clubs from here on
10 of 3
10 of 4
11 of 2
11 of 3
11 of 4
12 of 2
12 of 3
12 of 4
13 of 1 //back to normal here
13 of 2 //yes, including Clubs
13 of 3
13 of 4
14 of 1
14 of 2
14 of 3
14 of 4
答案 0 :(得分:2)
您的比较功能不正确,应该是(例如)
public func <(left: Card, right: Card) -> Bool {
// Compare `suit` first. If different, you are done.
if left.suit != right.suit {
return left.suit < right.suit
}
// Same `suit`, need to compare `rank`.
return left.rank < right.rank
}
假设您要先按suit
排序,然后按rank
排序。
代码中的错误是它无法正确处理案例left.rank > right.rank
。在这种情况下它应该返回false
,
但它实际上返回left.rank < right.rank
的结果。