在网格视图中从40个图像中随机显示25个图像

Use*_*ser 1 iphone

我正在创建一个iphone应用程序,我需要在其中创建25个图像的网格视图.我这样做是通过在一个数组中拍摄25张图像,并通过使用for循环显示它们,方法是在下面的代码中更改x轴和y轴的尺寸:

for(int i=0; i<25; i++)
    {
    if(i>0)
    {
        if(i%5==0)
        {
            xaxis=30;
            yaxis=yaxis+35;
        }
    }
        iconButton[i]=[UIButton buttonWithType:UIButtonTypeRoundedRect];
        iconButton[i].frame=CGRectMake(xaxis, yaxis, 50, 30);
        [iconButton[i] setBackgroundImage:[iconArray objectAtIndex:i] forState:UIControlStateNormal];
        [iconButton[i] addTarget:self action:@selector(changeImage:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:iconButton[i]];
        xaxis=xaxis+55;
    }
Run Code Online (Sandbox Code Playgroud)

它工作正常,但我有40张图像,我希望每次应用程序启动它应该从25张图像中随机选取25张图像.

我该怎么做,请帮帮我.

非常感谢您的帮助.关心iPhoneDeveloper11

小智 5

创建一个包含41个数字(0-40)的数组,使用部分Fisher-Yates shuffle对它们进行混洗, 并使用数组的前25个元素.

伪码(随机(x)返回从0到x的随机数)

array = [0, 1, 2, ..., 40]
for i in 0, 1, ..., 24 do
    swap array[i], array[i + random(40 - i)]
truncate array to 25 elements.
Run Code Online (Sandbox Code Playgroud)