i'm builing an hybrid app in Javascript that casually pick an exercise from a database, wait for the user to solve it and then pick another exercise.
Nothing difficult at this point, my problem is about picking always a different exercise from database.
Now my code 'works' in this way:
- Gets total number of exercises (about 3K),
- Generate a N random number from 1 to 3000,
- Pick the N exercise from DB,
- Save the N number in the 'used' db table,
- Generate another number name,
- This time first of all check if the generated number was already used,
- If NO pick exercise, if YES generate another number,
- etc...
The code works well for the first 2000-2500 numbers, then start to be really slow because generating a random number not already used starts to be very difficult. When the number used are just a bit less than 3K the code is totally broken: continues to check but the new number never comes
How can i handle this situation in a fast and light way that use memory as less as possible?
Thank you very much!
EDIT
I'm using WebSQL in a phonegap application
That's what i'm doing (code):
Here i get the number of the exercises
1. SELECT COUNT(*) AS countArt FROM Exercises'
Here i pick a random number from 1 to totalNumberOfExercises
2. randomNumber = random(totalNumberOfExercises);
function numeroCasuale(len){
var num = Math.floor(Math.random() * len) + 0;
return num;
};
Here i check if my randomNumber is already in the DB, that means is already used
4. SELECT EXISTS(SELECT * FROM alreadyUsed WHERE numero=randomNumber)
If randomNumber exists i generate another randomNumber and check it again and again...