Brief Idea about the flow :
I have say minimum 1 and maximum 18 records in my database with a text and an image from which I have to fetch images and place any 3 of the same randomly to 3 UIButtons
among which one image should match with my question. i.e. 1 is the answer and other 2 are the distractors.
For Example : Question is : where is Apple? Now among the bunch of images, I want to place any 3 images on the 3 UIButtons(1 answer i.e. An Apple and 2 distractors) in a random order and on selecting the UIButton it should prompt me if it's a right answer or not.
I am implementing below code for placing the UIImages in a random order :
-(void) placeImages
{
NSMutableArray *images = [NSMutableArray arrayWithArray:arrImg];
NSArray *buttons = [NSArray arrayWithObjects:btn1,btn2,btn3, nil];
for (UIButton *btn in buttons)
{
int randomIndex= random() % images.count;
UIImage *img = [images objectAtIndex:randomIndex];
[btn setImage:img forState:UIControlStateNormal];
[images removeObjectAtIndex:randomIndex];
}
}
But I am stuck at a point that how should I get 1 UIButton
image with an answer and other as distractors also that how should i maintain the index of the image from the NSArray
? Kindly guide me. Thank you.
set your first button to be the Apple (correct answer) set the remaining buttons to be random wrong answers, then position the buttons randomly in your app
Break it down into simpler problems:
Select three images from the set such that one is the answer and the other two are not the same and not the answer.
Assign the images to buttons in some random order.
Remember which button corresponds to the correct answer.
So, let's say that the entire set of images is given unique identifiers 0..n-1. You know which image is the answer for a given question, so add it's ID to an array. Randomly choose two more ID's and add them to the array, checking to make sure that neither is already in the array. Store the ID for the correct answer in an instance variable. That takes care of problem #1.
Now, shuffle the array. There are a number of questions here on SO that cover that, so I won't explain it here. Assign the first ID in the array to the first button's
tag
property; set that button's image to the image for that ID. Similarly set up the second button with the second ID from the array and it's image, and again for the third button. Ensure that all three buttons have the same target and action. Problem #2 solved.In the action method for the buttons, get the
tag
of the tapped button (which is thesender
parameter for the action). Compare the tag to the ID of the correct answer, which you previously stored in an instance variable. If they match, the user was correct. Problem #3 solved.