I'm currently making a quiz app. When a user starts the quiz random questions show up like you would expect from a quiz app. The problem is, it is not quite random. It does show random questions, but the questions repeat. I wanted to make sure they do not repeat until the end! My code is :
int Questions = arc4random_uniform(142);
switch (Questions) {
case 0:
break;
case 1:
break;
(...)
Isn't there a better way to do it? A way to just not repeat the questions? Thank you so much!
Put your questions in an array and put the random number in the
objectWithIndex
method ofNSMutableArray
. Then remove the question from the array. Whenever a index is chosen, but there is not a question anymore, try it again.Any random generator is actually pseudorandom. By default it is started from the same initial value. To make it it "real random" you should supply unique start value i.e. "salt" for each run. As a simplest approach you can use [NSDate timeIntervalSinceReferenceDate].
A shuffle may be your best solution:
ADDENDUM
Example with actual text being printed after shuffling
The idea is to use each question once until all questions have been used.
Sample code. Note that the questionIndex does not repeat.
NSLog output:
arrayIndex: 9, questionIndex: 9
arrayIndex: 5, questionIndex: 5
arrayIndex: 5, questionIndex: 6
arrayIndex: 3, questionIndex: 3
arrayIndex: 3, questionIndex: 4
arrayIndex: 4, questionIndex: 8
arrayIndex: 2, questionIndex: 2
arrayIndex: 0, questionIndex: 0
arrayIndex: 1, questionIndex: 7
arrayIndex: 0, questionIndex: 1