我有一个带有4个对象的NSArray,比如说1、2、3和4。我想按升序对该数组进行排序,但是要随机选择一个起始编号。例如; 2、3、4和1或4、1、2和3。
我怎样才能做到这一点?
到目前为止,我有:
NSArray *playersArray = [_players allKeys];
NSSortDescriptor *sortPlayerArray = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
playersArray = [playersArray sortedArrayUsingDescriptors:@[sortPlayerArray]];
这显然导致了1、2、3、4。我还可以随机订购玩家,如下所示:
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];
那么如何“组合”这两个以获得所需的结果?
希望你们能帮助我。
谢谢!
最佳答案
我认为这是@Konsol的意图,并进行了一些修复:(1)看起来OP希望顺序递增,(2)在另一个答案中拆分的数组在中点。但我认为这种精神是正确的...
// 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);
关于ios - 按降序对NSArray进行排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25899220/