I am working on a MCQ module and I need to fetch random questions from my database. The problem is that I seem to get duplicates.
-
Apologies for the edit race condition, RichBryeguy– ryeguy2009-03-23 16:39:12 +00:00Commented Mar 23, 2009 at 16:39
-
@ryeguy: I rolled back, as I think I have a better edit. Feel free to add on to mine.GEOCHET– GEOCHET2009-03-23 16:39:48 +00:00Commented Mar 23, 2009 at 16:39
-
do your questions change often, or are they mostly static?Greg Dean– Greg Dean2009-03-23 16:54:37 +00:00Commented Mar 23, 2009 at 16:54
-
@Greg — Well, if this one is any indication… ;-)Ben Blank– Ben Blank2009-03-23 17:15:56 +00:00Commented Mar 23, 2009 at 17:15
-
Looks like what you have is a database question, not a PHP question, depending how you want to execute this, please tell us what database you are using.TravisO– TravisO2009-03-23 19:06:23 +00:00Commented Mar 23, 2009 at 19:06
6 Answers
Sounds like you want to shuffle the questions, not randomize access to them. So your algorithm would be something like this.
- Get the all question (or question keys) you want to display.
- Shuffle them
- Retrieve/ display in them in the shuffled order
for shuffling check out: Fisher-Yates shuffle algorithm
Comments
If you're using MySql and you have reasonable small amount of data, you can use ORDER BY RAND()
1 Comment
See Do stateless random number generators exist?
Any sequence of pseudo-random numbers will eventually repeat. How you obtain your pseudo-random numbers?
Comments
Without any more info i can suggest a rudimentary solution. (but please update your question with more info)
I'm guessing you have users, because then you could save into a table (be it temporary or not), what questions said user has already gotten.
If you don't have users, you can use the SESSION_ID as a user identifier for that user.
So when you fetch a question for the first time, and the user answers it, it saves the info you need to save, and then the user's id and the question's id into a table.
When fetching the next question, you do a check to see if the user has that question id in this new table.
Comments
If you have a very large number of rows you can add a column to the table which stores a number between 0 and 1 and then fetch with a query:
SELECT * FROM `mytable` WHERE `randcolumn` > RAND() LIMIT 20
This means that your database doesn't have to randomly order the entire table to provide just 20 rows.