Click here to Skip to main content
14,387,969 members

Let's randomize IEnumerable

Rate this:
0.00 (No votes)
Please Sign up or sign in to vote.
0.00 (No votes)
12 Oct 2011CPOL
Shuffle in O(N) time, vastly faster than the original version that calls RemoveAt().static Random r = new Random();public static IEnumerable Randomize(this IEnumerable source){ var list = source.ToList(); for (int i = 0; i < list.Count; i++) Swap(list, i,...
Shuffle in O(N) time, vastly faster than the original version that calls RemoveAt().
static Random r = new Random();
public static IEnumerable<T> Randomize<T>(this IEnumerable<T> source)
{
	var list = source.ToList();
	for (int i = 0; i < list.Count; i++)
		Swap(list, i, r.Next(list.Count));
	return list;
}
public static void Swap<T>(List<T> list, int i, int j)
{
	T tmp = list[i];
	list[i] = list[j];
	list[j] = tmp;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Qwertie
Software Developer None
Canada Canada
Since I started programming when I was 11, I wrote the SNES emulator "SNEqr", the FastNav mapping component, the Enhanced C# programming language (in progress), the parser generator LLLPG, and LES, a syntax to help you start building programming languages, DSLs or build systems.

My overall focus is on the Language of your choice (Loyc) initiative, which is about investigating ways to improve interoperability between programming languages and putting more power in the hands of developers. I'm also seeking employment.

Comments and Discussions

 
GeneralNote: the standard versions of this algorithm might use "i+r... Pin
Qwertie12-Oct-11 9:58
MemberQwertie12-Oct-11 9:58 
GeneralRe: It improves the uniformity of the probabilities. Pin
Henry.Ayoola13-Oct-11 1:14
MemberHenry.Ayoola13-Oct-11 1:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Alternative
Tip/Trick
Posted 12 Oct 2011

Tagged as

Stats

8.1K views
1 bookmarked