在我的代码中,我想要对数组中的元素进行洗牌并尝试将其打印出来,但它并没有正确地进行洗牌,我尝试了显示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);
}
}
}
}
在洗牌之后重复数组值,请帮我解决这个问题
答案 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];
}
}