混淆NSMutableArray objective-c

3

3
请查看:https://dev59.com/wXVD5IYBdhLWcg3wL4mM - jussi
2
@Timur:是的,没错。这个答案https://dev59.com/wXVD5IYBdhLWcg3wL4mM#56656 恰好就是你想要的。 - JeremyP
我不想重新排列我的数组。我想要获取索引并将它们在另一个数组中重新排序。 - Timur Mustafaev
2
@Timur:好的,那就复制这个数组,然后对副本进行洗牌(使用“-mutableCopy”)。 - JeremyP
2个回答

4
请看下面的代码:
int length = 10; // int length = [yourArray count];
NSMutableArray *indexes = [[NSMutableArray alloc] initWithCapacity:length];
for (int i=0; i<10; i++) [indexes addObject:[NSNumber numberWithInt:i]];
NSMutableArray *shuffle = [[NSMutableArray alloc] initWithCapacity:length];
while ([indexes count])
{
    int index = rand()%[indexes count];
    [shuffle addObject:[indexes objectAtIndex:index]];
    [indexes removeObjectAtIndex:index];
}
[indexes release];
for (int i=0; i<[shuffle count]; i++)
    NSLog(@"%@", [shuffle objectAtIndex:i]);

现在在洗牌中,您将获得不重复的数组索引。
希望这能帮到您。

2
Nekto的回答很好,但我会更改两件事情:
1)使用arc4random()代替rand(),以获得不那么可预测的结果(更多细节here):
int index = arc4random() % [indexes count];

将“shuffle”的内容输出,使用[myArray description](无需使用for循环):
NSLog(@"shuffle array: %@", [shuffle description]);

为了更简化,调用 NSLog(@"shuffle array: %@", shuffle); 等同于 NSLog(@"shuffle array: %@", [shuffle description]);,因为 %@ 发送消息 description 给对象。 - PengOne

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接