Is there any reason why this loop is getting stuck? I can’t quite get my head around it:
var i:Number = -1;
do
{
i = Math.round(Math.random() * _totalQuestions);
}
while(_usedQuestions.indexOf(i));
Where _usedQuestions is an array of numbers. This array starts empty.
Thanks!
Edit: I want the loop to end if i is NOT found in the array.. this way I know the question I have selected has not previously been asked.
There are really two answers here.
The loop never exits because
Array.indexOf()returns-1if the argument is not found, and -1 is true in a boolean context. The only way your loop will ever exit is ifihappens to be equal to_usedQuestions[0].It may not be obvious, but even if you fix the above problem your loop will still fail to exit once all the questions have been used… and that’s your real problem – you’re using a confusing algorithm to do something simple.
It would make a lot more sense to simply keep two arrays – one of unseen questions and one of seen questions. Every time you choose a new question, simply remove it from
unseenand add it toseen. Like this:Remember: writing programs that work correctly is merely the minimum requirement of programming. A good programmer writes programs that are easily understood by people as well! And a big part of that is making sure that simple things are done in simple ways. (Unless performance is an inescapable factor – but in this case, I absolutely promise that it won’t!)