samedi 27 juin 2015

Fisher-Yates Algorithm Explanation?

I'm wondering if some of you understand how the Fisher-Yates shuffle works and can explain it to me. so I found this Fisher-Yates Shuffle code online:

public function Main() {
var tempArray:Array = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
public 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:Object = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;

That code works perfectly but I'm still confused

  1. I changed the loop to "input.length" and it doesn't work well, I still got "0" values sometimes. I have no idea why should I use "input.length-1" instead of "input.length"
  2. At the randomize section, why should I randomize the index from 0 to the value (i+1), why don't we just randomize it from 0 to (i) instead?

If some of you understand it, can you please explain it to me? Thank you so much

Aucun commentaire:

Enregistrer un commentaire