Hacker News new | ask | show | jobs
by songism 6062 days ago
This is how python's shuffle works:

  def shuffle(x):
    for i in reversed(xrange(1, len(x))):
      j = int(random() * (i+1))
      x[i], x[j] = x[j], x[i]
In the first loop the last element in the list 'x' has a chance to be exchanged with itself or any of the other elements. Then the second to last element has a chance to be exchanged with itself or any other element.

All the way down to the second to last element, which has the chance to be exchanged with itself or the first element.

This is exactly how the good Knuth shuffle algorithm works, right?