如何随机分配一个NSArray? [英] How to randomize an NSArray?

查看:117
本文介绍了如何随机分配一个NSArray?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个内含50-100个对象的NSArray.如何将数组随机排列?

Let's say I have a NSArray with 50-100 objects inside. How can I put the array in a random order?

推荐答案

有很多方法可以做到这一点,但是大多数方法仅涉及生成随机数.也许您可以通过NSMutableArray使用此技术:

There are a lot of ways to do it, but most will involve simply generating random numbers. Perhaps you could use this technique using an NSMutableArray:

  1. 生成一个介于0到49之间的随机数(假设有50个元素)
  2. 交换元素0和生成的任何数字
  3. 生成1到49之间的随机数
  4. 交换元素1和您生成的任何数字
  5. 等等.

那可能是最有效的方法.

That would probably be the most efficient way.

示例代码(未经测试):

Sample code (not tested):

srandom(time(NULL));
for (NSInteger x = 0; x < [array count]; x++) {
    NSInteger randInt = (random() % ([array count] - x)) + x;
    [array exchangeObjectAtIndex:x withObjectAtIndex:randInt];
}

此外,您可以使用两个NSMutableArray对象,并在第一个对象具有对象的情况下简单地循环遍历,随机选择一个,然后将其添加到另一个对象的末尾.不过,就地方法可能会更快.

Also, you could use two NSMutableArray objects, and simply loop through while the first has objects, choose one randomly, and add it to the end of the other one. The in place method is probably faster though.

这篇关于如何随机分配一个NSArray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆