问题
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