【问题标题】:How to move the elements of an array randomly in Objective-C [duplicate]如何在Objective-C中随机移动数组的元素[重复]
【发布时间】:2012-05-12 06:25:02
【问题描述】:

可能重复:
canonical way to randomize an NSArray in Objective-C

假设我有一个如下数组。

shuffleArray = [[NSMutableArray alloc] initWithObjects:@"A",@"B",@"C",@"D",@"E", nil];

我想随机改变数组元素的位置如下:

shuffleArray = [[NSMutableArray alloc] initWithObjects:@"C",@"A",@"B",@"E",@"D", nil];

那我该怎么做呢?

【问题讨论】:

标签: ios objective-c ios5


【解决方案1】:
-(NSArray *)shuffleme
{

 NSMutableArray *array = [NSMutableArray arrayWithCapacity:[self count]];

 NSMutableArray *array1 = [self mutableCopy];
 while ([array1 count] > 0)
 {
  int temp = arc4random() % [array1 count];
  id objectToMove = [array1 objectAtIndex:temp];
  [array addObject:objectToMove];
  [array1 removeObjectAtIndex:temp];
 }

   [array1 release];
   return array;
}

希望对你有所帮助..

【讨论】:

    【解决方案2】:
    -(void)changeObjectAtIndex:(int)index1 index2:(int)index2 array:(NSMutableArray *)array
    {
         id objectAtIndex1=[array objectAtIndex:index1];
         [array insertObject:[array objectAtIndex:index2] atIndex:index1];
         [array insertObject:id atIndex:index2];
    }
    

    这是为了在两个索引处交换对象,如果你确切地知道你想要特定对象的位置,你可以使这个函数递归。但是如果你想要它随机,那么你可以采用 Nit 的方法。

    随机也可以通过:-

    id newObject= [[[yourArray objectAtIndex:index] retain] autorelease];
    [yourArray  removeObjectAtIndex:index];
    [yourArray  insertObject:object atIndex:yourIndex];
    

    记住要保留对象。

    【讨论】:

      猜你喜欢
      • 2012-06-05
      • 2022-01-25
      • 2013-05-12
      • 2011-10-23
      • 2010-12-09
      • 1970-01-01
      • 1970-01-01
      • 2011-11-01
      相关资源
      最近更新 更多