I have an array of lights that I need to sample from randomly, but deterministically so that all the lights are sampled. Currently I use random numbers to pick a light, and then put processed lights into another list, but I'm wondering if there is a way to use something like a hammersly or halton sequence to do this instead. A biased solution would be ok.


1 Answer 1


If I understand this, the sequence:
could end up as:
3,2,4,1 or 1,3,2,4 or whatever?

Fisher-Yates Shuffle, or the Knuth Shuffle came up on wikipedia. It says linear time, which is good.

import random

def shuffle(x):
    for i in reversed(range(1, len(x))):
        # pick an element in x[:i+1] with which to exchange x[i]
        j = random.randrange(i+1)
        x[i], x[j] = x[j], x[i]
  • \$\begingroup\$ +1 for a simple in-place shuffle. This is the technique I have used when I needed to access all of the elements in a sequence exactly once, but in a randomized order. \$\endgroup\$ Nov 19, 2010 at 17:54

You must log in to answer this question.