PDA

View Full Version : AS3 Array, XML, Force Random



jamesbeith
February 27th, 2009, 12:18 PM
I have an XML file that is loaded in to Flash. Then from those ten questions in the XML file I want to randomly load 8 of them in to an array and ensure none of them are duplicates. It all works apart from I am getting duplicate questions put in to the array. Please help me solve this snippet of the code below so that the random number get regenerated if that related question is already in the array.




///// START QUESTION SELECTION /////

// new variables for questions functions
var numQuestions:int = 8; // number of questions to include in the quiz from the XML file
var questionArray:Array = new Array(numQuestions);
var i:int;
var j:int;
var RandNum:int;
var RandNum1:int;

// questions array function
function pickQuestions(TypeInput:XML):void {
for(i = 0; i < numQuestions; i++) {
questionArray[i] = new Array(3); // create three columns for each row

do {
RandNum = Math.random()*xmlData.Type.length(); // pick a new random number from length of XML file
} while(checker(RandNum) == -1)

questionArray[i][0] = TypeInput.Type.ID.text()[RandNum];
questionArray[i][1] = TypeInput.Type.Question.text()[RandNum];
questionArray[i][2] = TypeInput.Type.Answer.text()[RandNum];

// trace array
// trace("QUESTION NUMBER: " + i);
trace("XML ID: " + questionArray[i][0]);
// trace(questionArray[i][1]);
// trace(questionArray[i][2]);
trace("");
}
}

// function to ensure unique random questions
function checker(RandNum1) {
for (j = 0; j < questionArray.length; j++) {
if (RandNum1 == questionArray[i][0]) {
return (-1);
}
}
return (RandNum1);
}

///// END QUESTION SELECTION /////

wvxvw
February 27th, 2009, 05:25 PM
var questions:XML =
<questions>
<q id="0"/>
<q id="1"/>
<q id="2"/>
<q id="3"/>
<q id="4"/>
<q id="5"/>
<q id="6"/>
<q id="7"/>
<q id="8"/>
<q id="9"/>
</questions>;

function generateRandomQuestions(source:XML, nodes:int = 8):XMLList
{
if (source.*.length() < nodes) return source.*;
var list:XMLList;
var hash:Array = [];
var randomPosition:int;
var node:XML;
do
{
node = source.*[(Math.random() * source.*.length()) >> 0];
if (hash.indexOf(node.toXMLString()) < 0)
{
hash.push(node.toXMLString());
list ? list += node : list = XMLList(node);
}
} while (list.length() < nodes)
return list;
}

trace(generateRandomQuestions(questions).toXMLStri ng());
trace("--- only 3 questions ---");
trace(generateRandomQuestions(questions, 3).toXMLString());

gherry
June 18th, 2009, 02:34 PM
Hey, this is exactly what I was looking for, but it doesn't work with AS2, and I have no idea how to show the xml data on AS3, any clue?

What I need is to show the value of each XML item, one at a time until the user clics Next

Thanks in advance

Gherry:thumb2: