How to shuffle NSMutableArray without repetition [duplicate]

我是研究僧i 提交于 2019-12-13 08:24:18

问题


Possible Duplicate:
What’s the Best Way to Shuffle an NSMutableArray?

Here in my code I want to shuffle the elements in the array and try to print it out, but it's not shuffling properly, I tried what is shown here.Its working but,it values are repating.

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

            }
        }

    }

}

After shuffling the array values are repeating,pls help me to solve this issue


回答1:


Try this int n = (arc4random() % count);
instead of
int n = (arc4random() % nElements) + i;

Ensure that you are swapping current element with any element in the texts instead of an element which is always succeeding it.




回答2:


Just make the category of 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];
}

}



来源:https://stackoverflow.com/questions/13206426/how-to-shuffle-nsmutablearray-without-repetition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!