简体   繁体   English

按降序对NSArray进行排序

[英]Sort NSArray in descending order

I have an NSArray with 4 objects, let's say 1, 2, 3 and 4. I want to sort this array in ascending order, but with a randomly selected starting number. 我有一个带有4个对象的NSArray,比如说1、2、3和4。我想按升序对该数组进行排序,但是要随机选择一个起始编号。 For instance; 例如; 2, 3, 4 and 1 or 4, 1, 2 and 3. 2、3、4和1或4、1、2和3。

How can I do this? 我怎样才能做到这一点?

What I have thus far: 到目前为止,我有:

NSArray *playersArray = [_players allKeys];
NSSortDescriptor *sortPlayerArray = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
playersArray = [playersArray sortedArrayUsingDescriptors:@[sortPlayerArray]];

This results in 1, 2, 3, 4, obviously. 这显然导致了1、2、3、4。 I am also able to randomly order the players, like so: 我也可以随机订购玩家,如下所示:

activePlayersArray = [_players allKeys];
NSMutableArray *temp = [[NSMutableArray alloc] initWithArray:activePlayersArray];

int count = (int)[temp count];

for (int i = 0; i < count; ++i) {
    int nElements = count - i;
    int n = (arc4random() % nElements) + i;
    [temp exchangeObjectAtIndex:i withObjectAtIndex:n];
}

activePlayersArray = [NSArray arrayWithArray:temp];

So how can I "combine" these two to get the results I want? 那么,如何“组合”这两个以获得所需的结果?

Hope you guys can help me. 希望你们能帮助我。

Thanks! 谢谢!

This is really an algorithm problem, not an iOS problem. 这实际上是算法问题,而不是iOS问题。 Here are the steps to follow 这是要遵循的步骤


Another solution is to create a circular array of sorted elements and then traverse the array in reverse order. 另一个解决方案是创建一个排序元素的圆形数组,然后以相反的顺序遍历该数组。

I think this is what @Konsol intends, with a couple fixes: (1) it looks like the OP wants the order to be ascending, and (2) the array split in the other answer is at the midpoint. 我认为这是@Konsol的意图,并进行了一些修复:(1)看起来OP希望顺序递增,(2)在另一个答案中拆分的数组位于中间点。 But I think the spirit is correct... 但我认为这种精神是正确的...

// Start with an unsorted (immutable?) input array of numbers (or any object
// that implements compare:.
// Pick a random location and produce an output array as described by the OP

NSMutableArray *mutableArray = [inputArray mutableCopy]; // if its not mutable already
[mutableArray sortUsingSelector:@selector(compare:)];

NSInteger inputIndex=arc4random_uniform(mutableArray.count);    
NSArray *start = [mutableArray subarrayWithRange:NSMakeRange(inputIndex, mutableArray.count-inputIndex)];
NSArray *end = [mutableArray subarrayWithRange:NSMakeRange(0, inputIndex)];

NSArray *outputArray = [start arrayByAddingObjectsFromArray:end];
NSLog(@"%@", outputArray);
int count = (int)[activePlayersArray count];
int n = (arc4random() % nElements) + i;
NSMutableArray *temp = [[NSMutableArray alloc] init];
for (int i = 0; i < count; ++i) {
    int nElements = count - i;
    [temp addObject:[activePlayersArray objectAtIndex:(n-i)%count]];
}
activePlayersArray = [NSArray arrayWithArray:temp];

Hope it works! 希望它能起作用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM