【问题标题】:How to randomize an NSMutableArray? [duplicate]如何随机化 NSMutableArray? [复制]
【发布时间】:2011-06-06 16:52:02
【问题描述】:

可能重复:
iphone - nsarray/nsmutablearray - re-arrange in random order

我有一个包含 20 个对象的 NSMutableArray。有什么方法可以让我随机化他们的顺序,就像你洗牌一样。 (按顺序是指它们在数组中的索引)

如果我有一个包含以下内容的数组:

  1. 苹果
  2. 橙色
  3. 香蕉

我怎样才能随机化顺序以便我可以得到类似的东西:

  1. 橙色
  2. 苹果
  3. 香蕉

【问题讨论】:

    标签: objective-c nsmutablearray shuffle


    【解决方案1】:

    以下是一些示例代码: 遍历数组,随机切换一个对象的位置。

    for (int x = 0; x < [array count]; x++) {
        int randInt = (arc4random() % ([array count] - x)) + x;
        [array exchangeObjectAtIndex:x withObjectAtIndex:randInt];
    }
    

    【讨论】:

    • 感谢这个简单的代码。有用。我爱你。
    【解决方案2】:
    @interface NSArray (Shuffling)
    
    - (NSArray *)shuffledArray;
    
    @end
    
    @implementation NSArray (Shuffling)
    
    - (NSArray *)shuffledArray {
        NSMutableArray *newArray = [[self mutableCopy] autorelease];
    
        [newArray shuffle];
        return newArray;
    }
    
    @end
    
    @interface NSMutableArray (Shuffling)
    
    - (void)shuffle;
    
    @end
    
    @implementation NSMutableArray (Shuffling)
    
    - (void)shuffle {
        @synchronized(self) {
            NSUInteger count = [self count];
    
            if (count == 0) {
                return;
            }
    
            for (NSUInteger i = 0; i < count; i++) {
                NSUInteger j = arc4random() % (count - 1);
    
                if (j != i) {
                    [self exchangeObjectAtIndex:i withObjectAtIndex:j];
                }
            }
        }
    }
    
    @end
    

    但是请记住,这种洗牌是merely pseudorandom洗牌

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-25
      • 2011-12-28
      • 1970-01-01
      • 1970-01-01
      • 2011-08-11
      • 2011-11-10
      • 2012-10-23
      相关资源
      最近更新 更多