4 Replies Latest reply on Jun 10, 2015 8:56 AM by kglad

# Fisher-Yates Shuffle Algorithm error

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. Re: Fisher-Yates Shuffle Algorithm error

1.  Why do you keep shuffling each time? Once should be enough.

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

Why are you specifying an array as the startingIndex?  It should be an integer, not an array, and it looks like you'd want it to be 0 every time.

• ###### 2. Re: Fisher-Yates Shuffle Algorithm error

Yes, this fixes it:

 var quest: int = questions.splice(0, 1)[0];
• ###### 3. Re: Fisher-Yates Shuffle Algorithm error

Unless you have a reason, you should consider simplifying the code as it appears to be a bit of unnecessary overkill.  There is no reason to shuffle the data more than once, and after that you simply need to walk thru the array from start to finish, no need for splicing out pieces of it.

1 person found this helpful
• ###### 4. Re: Fisher-Yates Shuffle Algorithm error

that's not a correct implementation of fisher-yates and using a splice function is contrary to the purpose of using fisher-yates: an efficient minimal storage method of randomizing a finite group of objects.

i've posted as2 and as3 version many times. here's the as3 version again,

function shuffle(a:Array) {

var p:int;

var t:*;

var ivar:int;

for (ivar = a.length-1; ivar>=0; ivar--) {

p=Math.floor((ivar+1)*Math.random());

t = a[ivar];

a[ivar] = a[p];

a[p] = t;

}

}