%mathpiper,def="Shuffle"

//Retract("Shuffle",*);

/*
 This function is based on the Fisher-Yates/Knuth shuffle algorithm
 which is described here at 
 http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle .
*/
Shuffle(list) :=
[
    Check(IsList(list), "Argument", "Argument must be a list.");
    
    Local(index, randomIndex, temporary);
    
    list := FlatCopy(list);
    
    index := Length(list);
    
    While(index > 1)
    [
        randomIndex := RandomInteger(1,index);
        
        temporary := list[randomIndex];
        
        list[randomIndex] := list[index];
        
        list[index] := temporary;
        
        index--;
    ];      
    
    list;
];

%/mathpiper

    %output,preserve="false"
      Result: True
.   %/output





%mathpiper_docs,name="Shuffle",categories="User Functions;Statistics & Probability",access="experimental"
*CMD Shuffle --- randomly shuffles the elements in a list
*STD
*CALL
	Shuffle(list)

*PARMS

{list} -- a list of elements

*DESC
This function takes a list of elements and shuffles them.  A new
list with the shuffled elements is returned.

*E.G.
In> Shuffle({1,2,3,4,5})
Result: {5,1,2,4,3}

In> Shuffle({one,two,three})
Result: {two,three,one}

%/mathpiper_docs

    %output,preserve="false"
      
.   %/output


