我的应用程序视图显示一个包含16个数字的网格。每按一次按钮,我想要改变数字的排列,每次都是随机的。该应用程序通过16个小UIImageViews工作,每个UIImageViews都有一个与之关联的图像(数字)。目前,我通过生成随机数并使该数字与特定排列相对应来“随机化”该排列。像这样:
int number = rand() % 7;
if (number == 1) {
space1.image = three;
space2.image = ten;
space3.image = one;
space4.image = eight;
space5.image = two;
space6.image = five;
space7.image = thirteen;
space8.image = six;
space9.image = four;
space10.image = fifteen;
space11.image = sixteen;
space12.image = nine;
space13.image = fourteen;
space14.image = eleven;
space15.image = twelve;
space16.image = seven;
}
else if (number == 2) {
space1.image = ten;
................
.............etc
显然有数百万种可能的安排,而我在这里只捕获了其中的7种。任何人都可以建议一种真正随机化安排的方法吗?
我希望我已经足够清楚了。提前感谢您的帮助。
乔治
答案 0 :(得分:1)
您可以简单地实施Fisher-Yates shuffle算法。
您没有硬编码的多个组合,而是使用默认组合,当您对其应用算法时,它会转换为随机排列。
您可以通过这种方式实现它,例如:
NSMutableArray * space; // Array containing your UIImageViews
// Initial combination
[(UIImageView *)space[0] setImage:one];
[(UIImageView *)space[1] setImage:two];
...
[(UIImageView *)space[14] setImage:fifteen];
[(UIImageView *)space[15] setImage:sixteen];
[self fisherYatesShuffle:space];
FisherYates Shuffle的实施将是:
- (void)fisherYatesShuffle:(NSArray *) array {
for(int i = array.count - 1; i >= 0; i++) {
int j = arc4random() % i;
[space exchangeObjectAtIndex:i withObjectAtIndex:j];
}
}
答案 1 :(得分:1)
不是生成16个相同的实例变量,而是将UIImageView
对象存储在数组中,将UIImage
个对象存储在可变数组中,然后随机化图像数组的元素:
NSMutableArray *imageViews, *images;
imageViews = [[NSMutableArray alloc] init];
images = [[NSMutableArray alloc] init];
for (int i = 0; i < 16; i++) {
UImageView *imageView = [[UIImageView alloc] initWithFrame:someFrame];
[imageViews addObject:imageView];
[imageView release];
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"image_%d"], i];
[images addObject:image];
}
- (void)randomize
{
for (int i = 0; i < 100; i++) {
int idx1 = arc4random() % images.count;
int idx2 = arc4random() % images.count;
[images exchangeObjectAtIndex:idx1 withObjectAtIndex:idx2];
}
for (int i = 0; i < imagesViews.count) {
[[imageViews objectAtIndex:i] setImage:[images objectAtIndex:i]];
}
}
答案 2 :(得分:0)
在C中提示,因为这并不是您正在使用的Obj-C或IDE的特定内容。
Image images[n];
numbers = {0, 1, 2, /* ... n - 1 */ };
shuffle(numbers);
Images pmut[n];
for (int i = 0; i < n; ++i) {
pmut[i] = images[numbers[i]];
}