PDA

View Full Version : Arrays



dilpreet
June 9th, 2009, 02:37 AM
Hey i am making a quiz which is going to have 20 questions and i have about 40 question in the questions array. Now can you please tell me how to make a variable which will hold the 20 random question so

for eg

var arrQuestion:Array = [ 40 questions in here separated by commas]
var randQuestions:int = arrQuestion.length-1;

but that just sets randQuestions to the arrQuestion's length now how do i set the variable randQuestion with 20 questions that are randomly picked from arrQuestion.

excogitator
June 9th, 2009, 02:55 AM
I can tell you the logic if that helps.

Duplicate the 40 array into a new one
Pick a random number within 40
Delete that array index from the new array
now pick a random number with 39
Delete that array index from the new array
and so on repeat this 20 times in a loop reducing the random counter each time

So what you can say is we are deleting 20 questions from the 40 question array randomly
The final 20 questions that remain could be anything.

The remaining 20 questions can be used for the quiz.

Hope this helps unless someone posts a better solution :)

kirupa
June 9th, 2009, 03:18 AM
While I don't have one done for AS3 just yet, you can see a version I wrote a few years ago in C#: http://blog.kirupa.com/?p=111

My solution is possibly not as efficient as what excogitator suggests. In my solution, you create a new array that contains a randomized version of all 40 questions. In this new array, simply extract the first 20 questions.

Since all of the items in the array were randomized from what they were originally, the first twenty items are going to be different from the first twenty items you started off with.

:)

creatify
June 9th, 2009, 11:55 AM
per my last post - with some mods



// you'll change this to 20
var totalRandomQs:int = 5;

// per someone elses comment, I'd store anser and question in objects within one array, this array will not be modified, so you can always access it later in code if need be
var allQandA:Array = [{q:"Q0",a:"A0"},
{q:"Q1",a:"A1"},
{q:"Q2",a:"A2"},
{q:"Q3",a:"A3"},
{q:"Q4",a:"A4"},
{q:"Q5",a:"A5"},
{q:"Q6",a:"A6"},
{q:"Q7",a:"A7"},
{q:"Q8",a:"A8"},
{q:"Q9",a:"A9"},
{q:"Q10",a:"A10"},
{q:"Q11",a:"A11"}];


// create a new array by duplicating the allQandA array
var random5Questions:Array = [];
random5Questions = random5Questions.concat(allQandA);

function shuffle(a:*,b:*):int {
return int(Math.round(Math.random()*2)-1);
}
// shuffle that new array
random5Questions = random5Questions.sort(shuffle);

//then simply slice the array down to your totalRandomQs
random5Questions = random5Questions.slice(0,totalRandomQs);

// so this new array contains 5 items
trace("random5Questions.length: "+random5Questions.length);

var len:int = random5Questions.length;
for (var i:int=0; i<len; i++) {
trace(random5Questions[i].q.toString()+": "+random5Questions[i].a.toString());
}