0

可能重复:
洗牌 NSMutableArray 的最佳方法是什么?

在我的代码中,我想对数组中的元素进行洗牌并尝试将其打印出来,但它没有正确洗牌,我尝试了 这里显示的内容。它的工作但它的值正在重复。

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);

            }
        }

    }

}

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

4

2 回答 2

0

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

确保你正在用任何元素交换当前元素,texts而不是总是在它后面的元素。

于 2012-11-03T06:07:58.940 回答
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];
}

}

于 2012-11-03T06:12:30.000 回答