0

How would I create a random image generator that does not repeat images until it has been through them all once?

for example:

-(IBAction)randomimagebutton {

int randomimages = rand() % 5;

switch (randomimages) {

    case 0:
        imageview.image = [UIImage imageNamed:@"IMAGE_001.png"];
        break;
    case 1:
        imageview.image = [UIImage imageNamed:@"IMAGE_002.png"];
        break;
    case 2:
        imageview.image = [UIImage imageNamed:@"IMAGE_003.png"];
        break;
    case 3:
        imageview.image = [UIImage imageNamed:@"IMAGE_004.png"];
        break;
    case 4:
        imageview.image = [UIImage imageNamed:@"IMAGE_005.png"];
        break;

default:

        break;

}

If the images appeared in the order: 1,4,2,5,4,3 how could I make sure that the "4" would not appear again until all 5 images have been displayed?

Thanks for your help!

2 Answers2

1

Store the image names in an NSMutableArray and shuffle the array, e.g. via methods like this SO answer

Then loop over the array.

Community
  • 1
  • 1
Hugo
  • 494
  • 2
  • 7
0

Create a NSMutableArray and put 0, 1, 2, 3, 4 on it then whenever a random number is selected remove it like this:

[myNSMutableArray removeObjectAtIndex:myRandNumber];


To fill the gap, all elements beyond index are moved by subtracting 1 from their index.

Then simply select a new random by doing :

int randomimages = rand() % 4; //4 would of course be a int var that you substract everytime a new random is generated.

and so on.

Oscar Gomez
  • 18,436
  • 13
  • 85
  • 118