Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Lua
shuffled = {}
for i, v in ipairs(x) do
	local pos = math.random(1, #shuffled+1)
	table.insert(shuffled, pos, v)
end

Consider math.randomseed(os.time()) to get different sequences at each run.
function(x)
	for i = #x, 2, -1 do
		local j = math.random(i)
		x[i], x[j] = x[j], x[i]
	end
end

Fisher-Yates shuffle, in-place – for each position, pick an element from those not yet picked
#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...