Jump to content

User:Ilmari Karonen/sandbox

From Wikipedia, the free encyclopedia

A Fisher-Yates shuffle with zero-based arrays:

    i ← length( a ) − 1
    while i ≥ 1
        j ← rand( 0, i )
        ( ai, aj ) ← ( aj, ai )
        ii − 1
    repeat

Alternative notation:

    for i := length( a ) − 1 down to 1 step -1 do
        j := rand( 0, i );
        swap( ai, aj ) od;

Note: rand( a, b ) is assumed to return a uniformly distributed random integer from a to b inclusive.