3

I am helping my friend to develop a random fact app for iPhone which will be specific to certain areas of study.

My question is what is the best way to have say 100 or so facts and randomly generate them. I have a working prototype at the moment, but that just cycles through the facts using a NSMutableArray and an if loop.

What is the best way to randomize them so that every time the app is launched a different sequence appears? Should I be using a SQLite database?

PengOne
  • 48,188
  • 17
  • 130
  • 149
DKatri
  • 31
  • 2

2 Answers2

4

You could shuffle the array, save its state, and the position in the array. That way every time you opened the app, it would be a new fact, and you could shuffle when all the facts have been seen, so that way you have to see every fact at least once before you see any fact a second time.

Then you could save the facts in multiple files, named the area you want. So maybe, you have a Science file, a History file, etc. Then the facts would only show the facts specific to the category.

I disagree with the SQLite DB implementation because that has a lot of maintenance unless you save the file on a server and get the db info with some kind of refresh functionality.

To shuffle the array, add a category to your class for NSMutableArray in your header file

@interface NSMutableArray (Shuffle)
-(void)shuffle;
@end

In your implementation file, add the category and the code:

@implementation NSMutableArray (Shuffle)
-(void)shuffle {

   for(int pivot = 0; pivot < [self count]; pivot++) {
       int index = arc4random() % [self count];

       [self exchangeObjectAtIndex:pivot withObjectAtIndex:index];
   }
}
@end

To save your array, and its location:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:arrayOfFacts forKey:@"Array"] //arrayOfFacts is the array that has the facts in it
[defaults setInteger:arrayPosition forKey:@"Array Position"]; //arrayPosition is the fact number you are on

Then, in your viewDidLoad, or where ever you are loading your objects, load from the NSUserDefaults:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
arrayPosition = [defaults integerForKey:@"Array Position"];
arrayOfFacts = [defaults stringArrayForKey:@"Array"];
ColdLogic
  • 7,206
  • 1
  • 28
  • 46
  • +1 Great point *"see every fact at least once before you see any fact a second time"* – Raj More Jul 21 '11 at 19:14
  • How would I go about shuffling then saving the state and the position? I'm pretty new to Objective C so I'm sorry if this question has a really obvious answer. – DKatri Jul 22 '11 at 22:50
  • Sorry about the late response, it was the weekend :P. I added code to my answer to point you in the right direction. Ask away if something doesn't make sense to you. – ColdLogic Jul 25 '11 at 16:29
1

Put your strings in SQLite, yes.

Then the query you want is:

SELECT * FROM table ORDER BY RANDOM() LIMIT 1;
Dan Ray
  • 21,623
  • 6
  • 63
  • 87