【发布时间】:2013-12-19 06:11:36
【问题描述】:
最初我已经对数组元素进行了洗牌。现在如何按明确的顺序对这些数组元素进行排序。这是用于 iOS 中的纸牌游戏。
【问题讨论】:
-
你没有表现出你的努力。显示到目前为止您尝试了什么
标签: ios objective-c
最初我已经对数组元素进行了洗牌。现在如何按明确的顺序对这些数组元素进行排序。这是用于 iOS 中的纸牌游戏。
【问题讨论】:
标签: ios objective-c
您可以使用sortedArrayUsingComparator:对数组进行排序
[cards sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2)
{
Card *c1 = (Card *)obj1;
Card *c2 = (Card *)obj2;
if (c1.value == c2.value) return NSOrderedSame;
return (c1.value > c2.value) ? NSOrderedDescending : NSOrderedAscending;
}];
【讨论】:
您有几个选择,您可以查看 NSArray 文档 here 并查看“排序”下的内容。
如需快速了解,您可以使用 NSSortDescriptors
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"distance" ascending:YES];
NSArray *sortedArray = [shuffledArray sortedArrayUsingDescriptors:@[sortDescriptor]];
它们易于使用,您可以添加多个排序描述符。 你也可以使用比较器
[sortedArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
// Do your check here and return values below
// NSOrderedSame
// NSOrderedDescending
// NSOrderedAscending
}];
编辑:
好的,根据我从下面的 cmets 中了解到的是,您是一个包含最初洗牌的卡片的数组。
NSArray *shuffledCards
我猜你在那个数组中有 Card 对象。如果你不这样做,我认为你应该这样做。然后有四名球员。我再次相信你有 Player 对象。
举个例子:
@interface Card : NSObject
@property (nonatomic) NSInteger cardNumber;
@end
@interface Player : NSObject
@property (nonatomic) NSArray *dealtCards;
@end
假设您从洗好的数组中随机选择 10 张牌并将它们发给每个玩家。
NSArray *randomTenCards = // You get 10 cards somehow
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"cardNumber" ascending:YES];
NSArray * sortedCards = [randomTenCards sortedArrayUsingDescriptors:@[sortDescriptor]];
// The Card objects are now sorted inside sortedCards array according to their cardNumbers.
[self.player1 setDealtCards:sortedCards];
...
...
基本思路是这样的。我希望你可以根据自己的问题调整它。
【讨论】: