This language bar is your friend. Select your favorite languages!

Idiom #10 Shuffle a list

Generate a random permutation of the elements of list x

import scala.util.Random
val items = List(1, 2, 3, 4, 5)
val shuffledItems = Random.shuffle(items)
#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;
}
(shuffle collection)
#include <algorithm>
#include <vector>
std::random_shuffle(my_collection.begin(), my_collection.end());
System;
System.Collections.Generic;
private static Random rng = new Random();  

public static void Shuffle<T>(this IList<T> list)  
{  
    int n = list.Count;  
    while (n > 1) {  
        n--;  
        int k = rng.Next(n + 1);  
        T value = list[k];  
        list[k] = list[n];  
        list[n] = value;  
    }  
}
import std.random;
randomShuffle(x);
x.shuffle();
var shuffled = x.toList()..shuffle();
y = Enum.shuffle x
[Y||{_,Y} <- lists:sort([ {rand:uniform(), N} || N <- X])].
import "math/rand"
for i := range x {
	j := rand.Intn(i + 1)
	x[i], x[j] = x[j], x[i]
}
import "math/rand"
y := make([]T, len(x))
perm := rand.Perm(len(x))
for i, v := range perm {
	y[v] = x[i]
}
import "math/rand"
rand.Shuffle(len(x), func(i, j int) {
	x[i], x[j] = x[j], x[i]
})
shuffle x = if length x < 2 then return x else do
	i <- System.Random.randomRIO (0, length(x)-1)
	r <- shuffle (take i x ++ drop (i+1) x)
	return (x!!i : r)
for (var i in items) {
   var j = Math.floor(items.length * Math.random()),
        tmp = items[i]; items[i]=items[j]; items[j]=tmp;
}
for (var i = x.length - 1; i > 0; i--) {
    var j = Math.floor(Math.random() * (i + 1));
    var temp = x[j];
    x[j] = x[i];
    x[i] = temp;
}
import java.util.Collections;
Collections.shuffle(x);
shuffled = {}
for i, v in ipairs(x) do
	local pos = math.random(1, #shuffled+1)
	table.insert(shuffled, pos, v)
end
function(list)
	for i = #list, 2, -1 do
		local j = math.random(i)
		list[i], list[j] = list[j], list[i]
	end
end
shuffle($x);
var Iter,rr: integer; 
[...]
  for Iter := 0 to high(List) do
    begin
      rr := random(high(List))+1;
      tmp := List[Iter];
      List[Iter] := List[rr];
      List[rr] := tmp;
    end;
use List::Util 'shuffle';
@shuffled = shuffle('a', 'b', 'c', 'd', 'e', 'f');
from random import shuffle
shuffle(x)
import random
random.shuffle(list)
x.shuffle
shuffled_list = x.shuffle
extern crate rand;
use rand::{Rng, StdRng};
let mut rng = StdRng::new().unwrap();
rng.shuffle(&mut x);
extern crate rand;
use rand::{thread_rng, Rng};
let mut rng = thread_rng();
let mut y = [1, 2, 3];
rng.shuffle(&mut y);
(shuffle x)

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org

Related idioms