user1646089
user1646089

Reputation: 21

How do I randomize the questions pulled from my dictionary-plist

Hey Guys any ideas for randomising the questions that I pull from my -plist file?

-(NSUInteger)nextQuestionID:(NSUInteger)question_number{
return (question_number>=[self.questions count]-1) ? 0 : (question_number+1);
return 0;

}

-(NSDictionary*) getQuestion:(NSUInteger)question_number{
if (question_number>=[self.questions count]) question_number = 0;
return [self.questions objectAtIndex:question_number];
return NULL;


}

Upvotes: 2

Views: 112

Answers (5)

holex
holex

Reputation: 24031

the random integers:

srand(time(nil));
for (int i = 0; i < 100; i++) {
    NSLog(@"random number between 72 and 96 : %d", rand() % (96 - 72) + 72);
}

UPDATE

and for your specific case:

- (NSUInteger)nextQuestionID {
    srand(time(nil));
    return rand() % [self.questions count];
}

- (NSDictionary*)getQuestion {
    return [self.questions objectAtIndex:[self nextQuestionID]];
}

UPDATE#2

test the following loop two, three or more times and compare the outputs:

srand(time(nil));
for (int i = 0; i < 10; i++) {
    NSLog(@"random number : %d", rand() % 89 + 10);
}

you should get 10 random numbers between 10 and 99, I've tested it on a real device, not on the simulator but it should work on the simulator as well.

if you get the same result always, let me know.

Upvotes: 0

Vimal Venugopalan
Vimal Venugopalan

Reputation: 4091

set question number as random number

replace the function

-(NSDictionary*) getQuestion:(NSUInteger)question_number{
   if (question_number>=[self.questions count]) question_number = 0;
   question_number = arc4random()%[self.questions count];// changes made here
   return [self.questions objectAtIndex:question_number];
   return NULL;


}

Upvotes: 0

MaTTP
MaTTP

Reputation: 953

You can use the arc4random_uniform(upper_bound) function. The parameter is the upper bound of your random number.

An example:

int index = arc4random_uniform([self.question count]);

Upvotes: 1

AliSoftware
AliSoftware

Reputation: 32681

question_number = arc4random() % self.questions.count;

Upvotes: 0

MCKapur
MCKapur

Reputation: 9157

To get a random integer, I would suggest using arc4random function, here is some code to do this:

int randomInt = arc4random() % questionNumber;
return [self.questions objectAtIndex: randomInt];

Upvotes: 1

Related Questions