in reply to Extract random records from text file

Your question selector is broken, even if you arrange for one question per line.

Question 1 will be pushed into the array.
Question 2 has a 1/2 chance of being pushed.
Question 3 has a 1/3 chance of being pushed.

If you (for example) only want 2 questions, then you've now got a 5/6 chance of having selected them. So question 4 will only be tested 1/6 of the time, and then get pushed 1/4 of that: a total selectability of 1/24, not the 1/4 you intended.

if you really want to get all the questions in a single pass through the file, then you need to determine whether to keep the question (using rand), and then push the relevant details into a stack. At the end pop the last N elements off and use them.

That's esentially what the trick in the Cookbook does, but it uses a simple stack, of only one entry (aka a variable ;)

  • Comment on Re: Extract random records from text file