我正在尝试随机化数组中的数字。我可以使用 arc4random() % [indexes count]
来做到这一点
我的问题是 - 如果一个数组由 20 个项目组成,则每次数组洗牌时,在 5 个批处理中,应该出现不同的数字。示例:
第一次随机播放:1,4,2,5,6。
第二次随机播放:7,12,9,15,3
-(IBAction)randomNumbers:(UIButton *)sender
{
int length = 10; // int length = [yourArray count];
NSMutableArray *indexes = [[NSMutableArray alloc] initWithCapacity:length];
for (int i=0; i<5; i++)
[indexes addObject:[NSNumber numberWithInt:i]];
NSMutableArray *shuffle = [[NSMutableArray alloc] initWithCapacity:length];
while ([indexes count])
{
int index = arc4random() % [indexes count];
[shuffle addObject:[indexes objectAtIndex:index]];
[indexes removeObjectAtIndex:index];
}
// for (int i=0; i<[shuffle count]; i++)
NSLog(@"%@", [shuffle description]);
}
最佳答案
根据您的要求......请检查此代码
将其设为属性
@synthesize alreadyGeneratedNumbers;
将这些方法添加到您的 .m
-(int)generateRandomNumber{
int TOTAL_NUMBER=20;
int low_bound = 0;
int high_bound = TOTAL_NUMBER;
int width = high_bound - low_bound;
int randomNumber = low_bound + arc4random() % width;
return randomNumber;
}
-(IBAction)randomNumbers:(UIButton *)sender
{
NSMutableArray *shuffle = [[NSMutableArray alloc] initWithCapacity:5];
BOOL contains=YES;
while ([shuffle count]<5) {
NSNumber *generatedNumber=[NSNumber numberWithInt:[self generateRandomNumber]];
//NSLog(@"->%@",generatedNumber);
if (![alreadyGeneratedNumbers containsObject:generatedNumber]) {
[shuffle addObject:generatedNumber];
contains=NO;
[alreadyGeneratedNumbers addObject:generatedNumber];
}
}
NSLog(@"shuffle %@",shuffle);
NSLog(@"Next Batch");
if ([alreadyGeneratedNumbers count] >= TOTAL_NUMBER) {
NSLog(@"\nGame over, Want to play once again?");//or similar kind of thing.
[alreadyGeneratedNumbers removeAllObjects];
}
}
我仍然觉得你需要一些改变,比如
它会给你正确的值,但是如果用户按第五次怎么办?
在 20 个号码中,您已经选择了 4 组,每组 5 个号码,在第 6 次时,它将循环搜索下一组号码,并且将变为无限。
所以你可以做的是,保持随机播放的轨迹,一旦达到限制,即 20/5=4,禁用随机按钮。
关于objective-c - 如何生成不重复的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13640208/