开发者

To show 25 images randomly out of 40 images in a grid view

I am creating an iphone app in which I need to create a grid view of 25 images. I am doing that by taking 25 images in an array, and displaying them by using for loop by changing the dimensions for x axis and y axis in below code:

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] addTa开发者_如何学Gorget:self action:@selector(changeImage:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:iconButton[i]];
        xaxis=xaxis+55;
    }

It working fine but I have total 40 images with me and I want every time when application will launch it should pick the 25 images randomly out of that 25 images.

How will I do that, please help me.

Many Thanks in advance for your help. Regards iPhoneDeveloper11


Create an array of 41 numbers (0-40), shuffle them using a partial Fisher-Yates shuffle and use the first 25 elements of the array.

Pseudo-code (random(x) returns a random number from 0 to x inclusive):

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.


int random = arc4random() % 40;

gives a random number between 0 to 40, from that you choose the image


You essentially want to randomize the order of the images and then pick the first 25. I don't know exactly how you are arranging your data structures, but here is an example with integers:

for (int x = 39; x > 0; x--)
{
  int tmp = element[x];
  int newLoc = random()%(x+1);
  element[x] = element[newLoc];
  element[newLoc] = tmp;
}

I'm assuming that element contains your values that you want to mix up.


  1. create a set
  2. create a random number between 0 and 40 and put it in set
  3. check set size
  4. if set size is less than 25, go to step 2
  5. convert set to array

This is one way to do it and certainly there are better and faster ways, but if you want simplicity, use something like this or peoro's suggestion.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜