如何在不重复的情况下改组NSMutableArray

时间:2012-11-03 05:51:44

标签: iphone ios nsmutablearray

  

可能重复:
  What’s the Best Way to Shuffle an NSMutableArray?

在我的代码中,我想要对数组中的元素进行洗牌并尝试将其打印出来,但它并没有正确地进行洗牌,我尝试了显示here的内容。它的工作原理但它的值正在重复。< / p>

for(UIView *view in self.view.subviews)
{
    if([view isKindOfClass:[UIButton class]])
    { 
        button= (UIButton *)view;
        if (button.tag >=1 && button.tag <=20)
        {
            for (NSUInteger i = 0; i < count; ++i)
            {
                [texts rotate];
                // Select a random element between i and end of array to swap with.
                int nElements = count - i;
                int n = (arc4random() % nElements) + i;
                [texts exchangeObjectAtIndex:i withObjectAtIndex:n];
                //int myTag= j+1;
                //button = [self.view viewWithTag:myTag];
                name=[NSString stringWithFormat:@"%@",[texts objectAtIndex:n]];
                [button setTitle:name forState:UIControlStateNormal];
                NSLog(@"current  name :%@",name);

            }
        }

    }

}

在洗牌之后重复数组值,请帮我解决这个问题

2 个答案:

答案 0 :(得分:0)

试试这个int n = (arc4random() % count);
而不是
    int n = (arc4random() % nElements) + i;

确保使用texts中的任何元素而不是始终在其后面的元素交换当前元素。

答案 1 :(得分:0)

只需输入NSMutableArray的类别

即可
@implementation NSMutableArray (ArrayUtils)
-(void)shuffle
{
static BOOL seeded = NO;
 if(!seeded)
{
    seeded = YES;
    srandom(time(NULL));
}

NSUInteger count = [self count];
for (NSUInteger i = 0; i < count; ++i) {
    // Select a random element between i and end of array to swap with.
    int nElements = count - i;
    int n = (random() % nElements) + i;
    [self exchangeObjectAtIndex:i withObjectAtIndex:n];
}

}

相关问题