我有一个带有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];
那么我怎样才能“结合”这两个来获得我想要的结果呢?
希望你们能帮帮我。
谢谢!
答案 0 :(得分:3)
这实际上是一个算法问题,而不是iOS问题。以下是要遵循的步骤
另一个解决方案是创建一个排序元素的循环数组,然后以相反的顺序遍历数组。
答案 1 :(得分:1)
我认为这是@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);
答案 2 :(得分:0)
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];
希望它有效!