Friday, April 24, 2015

shuffle

Fisher-Yates shuffle, revised by Knuth edition. O(n) time.

note: rng.next(min, max) can return a -ve value.
shuffle(a):
    return shuffle(a.copy(), new rng())

// ok to modify buffer array
shuffle(buffer, rng):
    for i = buffer.length -1, i >= 0, i--:
        // rng.next(i) returns 0 to i-1, rng.next(0) is invalid
        swapindex = rng.next(i +1)
        yield return buffer[swapindex]
        // no need to swap fully as buffer[i] is not used after this iteration
        buffer[swapindex] = buffer[i]

No comments:

Post a Comment