Click here to Skip to main content
15,443,281 members
Articles / Programming Languages / C#
Tip/Trick
Posted 9 Oct 2011

Tagged as

Stats

23.6K views
2 bookmarked

Let's randomize IEnumerable

Rate me:
Please Sign up or sign in to vote.
4.75/5 (4 votes)
9 Oct 2011CPOL
I needed to randomize a collection. Here's my solution.
I needed to randomize an enumerable collection. Here's what I came up with in the 60 seconds I thought it deserved.

Your challenge:

  1. Do it better. better = faster with same number of items and/or faster with n items.

  2. Prove it.

C#
using System;
using System.Collections.Generic;

/// <summary>
/// Extension class for IEnumerable&lt;T&gt;
/// </summary>
static class IEnumerableExtension
{
    /// <summary>
    /// Randomizes the specified collection.
    /// </summary>
    /// <typeparam name="T">The type of the collection.</typeparam>
    /// <param name="collection">The collection.</param>
    /// <returns>The randomized collection</returns>
    public static IEnumerable<T> Randomize<T>(this IEnumerable<T> collection)
    {
        // Put all items into a list.
        var list = new List<T>(collection);
        var randomizer = new Random();
        // And pluck them out randomly.
        for (int i = list.Count; i > 0; i--)
        {
            int r = randomizer.Next(0, i);
            yield return list[r];
            list.RemoveAt(r);
        }
    }
}

License

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


Written By
Systems Engineer Clearpath Robotics
Canada Canada
Yvan Rodrigues has 30 years of experience in information systems and software development for the industry. He is Senior Controls Engineer at OTTO Motors

He is a Certified Technician (C.Tech.), a professional designation granted by the Institute of Engineering Technology of Ontario (IETO).

Yvan draws on experience as owner of Red Cell Innovation Inc., Mabel's Labels Inc. as Manager of Systems and Development, and the University of Waterloo as Information Systems Manager.

Yvan supports open-source software. He is a committer for SharpKit (C# to Javascript cross-compiler) and WebIssues (Issue/Ticket Management System), TinyMCE (JavaScript editor), and contributes to MySQL, Ghostscript, iTextSharp, Bacula, FreeBSD, and Xamarin.

Comments and Discussions

 
GeneralRe: Yes, but it would be algorithmically better. You're essentia... Pin
Henry.Ayoola13-Oct-11 0:12
MemberHenry.Ayoola13-Oct-11 0:12 
GeneralRe: The OP's code is O(n^2) unless List has some really sophisti... Pin
Henry.Ayoola13-Oct-11 0:11
MemberHenry.Ayoola13-Oct-11 0:11 
The OP's code is O(n^2) unless List has some really sophisticated RemoveAt logic.
GeneralRe: Good points! The problem that both solutions face is that b... Pin
Yvan Rodrigues11-Oct-11 4:21
professionalYvan Rodrigues11-Oct-11 4:21 
GeneralReason for my vote of 4 Simple idea but efficacious! Pin
SandroBoz10-Oct-11 21:43
MemberSandroBoz10-Oct-11 21:43 
Generalhttp://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Th... Pin
Henry.Ayoola10-Oct-11 3:03
MemberHenry.Ayoola10-Oct-11 3:03 
GeneralRe: I did exactly what the OP did before I discovered the Fisher... Pin
Wjousts11-Oct-11 3:38
MemberWjousts11-Oct-11 3:38 

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.