Fisher-Yates Shuffle Algorithm error

213 Views Asked by At

so I'm currently making a quiz game with Actionscript 3.0, and I wanna shuffle the questions with this Fisher-Yates Shuffle Algorithm:

This is my code:

var questions:Array = [1,2,3,4,5,6,7,8,9,10];
function ShuffleArray(input:Array)
{
    for (var i:int=input.length-1; i>=0; i--)
    {
        var randomIndex:int = Math.floor(Math.random() * (i+1));
        var itemAtIndex:int = input[randomIndex];
        input[randomIndex] = input[i];
        input[i] = itemAtIndex;
    }
}

function buttoncorrect(event:MouseEvent):void
{
ShuffleArray(questions);
trace (questions);
var quest:int = questions.splice(questions, 1)[0];
trace(quest);
}

btntry.addEventListener(MouseEvent.CLICK,buttoncorrect);

And here is the trace result:

9,7,5,10,4,8,6,2,1,3
9
7,1,2,6,8,10,5,4,3
7
5,2,3,10,6,1,8,4
5
4,3,10,6,2,8,1
4
2,1,8,3,6,10
2
10,8,6,1,3
10
3,8,6,1
3
1,8,6
1
6,8
6
8
0

Why do I always get the "0" value at the end? I should've get the value of "8" right? Does someone know what's wrong with my code? Thank you.

1

There are 1 best solutions below

0
On BEST ANSWER

The problem is this line:

var quest:int = questions.splice(questions, 1)[0];

The first parameter to splice() is supposed to be a start index. Since you want to remove the first element, it should be zero:

var quest:int = questions.splice(0, 1)[0];

The reason your code works for each case except the last one is because of the way automatic type conversion from Array to int works. ActionScript is automatically converting the array passed as the first parameter to a zero when it has more than one element, but converts it to the value of the only element in the array when it has a single element. So it is effectively:

var quest:int = questions.splice(0, 1)[0];

right up until the last call, when you pass in an array containing the single value 8. Then the last time it gets called, you are effectively doing this:

var quest:int = questions.splice(8, 1)[0];

Since that index is beyond the end of the array, an empty array is returned and traces out as 0.