1

I am able to display 5 images out of 8 from an array. But am getting repeated images with this code:

int index1 = arc4random()%8;
UIImage *card1=[UIImage imageNamed:[imageArray objectAtIndex:index1]];
[b1 setImage:card1 forState:UIControlStateNormal];

int index2 = arc4random()%8;
UIImage *card2=[UIImage imageNamed:[imageArray objectAtIndex:index2]];
[b2 setImage:card2 forState:UIControlStateNormal];

int index3 = arc4random()%8;
UIImage *card3=[UIImage imageNamed:[imageArray objectAtIndex:index3]];
[b3 setImage:card3 forState:UIControlStateNormal];

int index4 = arc4random()%8;
UIImage *card4=[UIImage imageNamed:[imageArray objectAtIndex:index4]];
[b4 setImage:card4 forState:UIControlStateNormal];

int index5 = arc4random()%8;
UIImage *card5=[UIImage imageNamed:[imageArray objectAtIndex:index5]];
[b5 setImage:card5 forState:UIControlStateNormal];
EmptyStack
  • 51,274
  • 23
  • 147
  • 178
  • check the function in the question : http://stackoverflow.com/questions/9798647/objective-c-uibutton-image-with-nsarray-in-a-random-order – Yama Mar 22 '12 at 06:54

1 Answers1

0

Create an NSMutableArray with your original array then shuffle it. For shuffling you can use this code:

//  NSMutableArray_Shuffling.h

#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#else
#include <Cocoa/Cocoa.h>
#endif

// This category enhances NSMutableArray by providing
// methods to randomly shuffle the elements.
@interface NSMutableArray (Shuffling)
- (void)shuffle;
@end


//  NSMutableArray_Shuffling.m

#import "NSMutableArray_Shuffling.h"

@implementation NSMutableArray (Shuffling)

- (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];
    }
}

@end

You can use shuffling like that:

NSMutableArray* array = [NSMutableArray arrayWithArray:imageArray];
[array shuffle];
[array objectAtIndex:0];
[array objectAtIndex:1];
[array objectAtIndex:2];
[array objectAtIndex:3];
[array objectAtIndex:4];
...

Shuffling code came from this question

Community
  • 1
  • 1
Behlül
  • 3,412
  • 2
  • 29
  • 46