I always use Fisher-Yates shuffle method to randomise an Array, which
yields more unbiased result.
http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
My AS3 interpretation of Fisher-Yates is as follows; I can just call
this from anywhere in my scripts ;)
package utils {
public function fisherYates(arr:Array):void {
var i:uint = arr.length;
while(--i){
var j:uint = Math.floor(Math.random()*(i + 1));
var tmpI:Object = arr[i];
var tmpJ:Object = arr[j];
arr[i] = tmpJ;
arr[j] = tmpI;
}
}
}
--
Kenneth Kawamoto
http://www.materiaprima.co.uk/
On 6 May 2010 02:27, Juan Pablo Califano
<[email protected]> wrote:
> A simple way:
>
> Put all the candidate numbers in a list (in this case, 1 to 40). Then pick
> randomly from that array, one at the time, and make sure you remove that
> number from the candidates list, so you can't have duplicates.
>
> In code (untested):
>
> function getRandomList():Array {
> var min:Number = 1;
> var max:Number = 40;
> var numItems:Number = 10;
> var candidates:Array = [];
> // fill up the candidates list with the "eligible" numbers
> for(var i:Number = min; i <= max; i++) {
> candidates.push(i);
> }
>
> var list:Array = [];
> var idx:Number = 0;
> var selectedNumber:Number = 0;
> for(i = 0; i < numItems; i++) {
> // get a number from the candidates list, randomly. Add it to the
> result and remove it from the candidates list (using splice)
> idx = Math.floor(Math.random() * candidates.length);
> selectedNumber = candidates.splice(idx,1)[0];
> list.push(selectedNumber);
> }
> return list;
> }
>
>
> Cheers
> Juan Pablo Califano
>
> 2010/5/5 Alan Neilsen <[email protected]>
>
>> I am working in ActionScript 2. I want to create a quiz in which 10
>> questions are randomly selected from a block of 40 questions. I found the
>> following code, but I can't work out how to stop it doubling up the
>> questions.
>>
>> function randRange(min:Number, max:Number):Number {
>> var randomNum:Number = Math.floor(Math.random() * (max - min + 1)) +
>> min;
>> return randomNum;
>> }
>> for (var i = 0; i < 10; i++) {
>> var n:Number = randRange(1, 40)
>> trace(n);
>> }
>>
>> When I run this it outputs a list of numbers like 40 13 17 12 27 12 3
>> 17 9 15 which means some questions (in this case 17 and 12) will appear
>> twice in my quiz.
>> Bearing in mind that I am a bit of an ActionScript dummy, can anybody
>> suggest a way to modify the above script to prevent the same number being
>> generated more than once.
_______________________________________________
Flashcoders mailing list
[email protected]
http://chattyfig.figleaf.com/mailman/listinfo/flashcoders