Logo

Programming-Idioms

  • Groovy
module M_shuffle
contains
function scramble( number_of_values ) result(array)
   integer,intent(in)    :: number_of_values
   integer,allocatable   :: array(:)
   array=[(i,i=1,number_of_values)]
   n=1; m=number_of_values
   do k=1,2
    do i=1,m
     call random_number(u)
     j = n + FLOOR((m+1-n)*u)
     itemp=array(j); array(j)=array(i); array(i)=itemp
    enddo
   enddo
end function scramble
end module M_shuffle
 :
use M_shuffle, only : scramble
newlist=list(scramble(size(list))

The SCRAMBLE function returns an integer array of the size specified
populated with the numbers 1 to "number_of_values" in random order.

A simple way to randomly scramble a list of any type is to create a
random permutation of all the index values of the array and then access
the original list elements using that list of indices. The list itself
can be re-ordered very succintly using array syntax.
x.shuffle()

Shuffles list in place.
Since Groovy 3.
#include <stdlib.h>
#include <time.h>
srand(time(NULL));
for (int i = 0; i < N-1; ++i)
{
    int j = rand() % (N-i) + i;
    int temp = x[i];
    x[i] = x[j];
    x[j] = temp;
}

Shuffles an array of n ints in-place using Fisher-Yates algorithm.

New implementation...