I needed to randomize an enumerable collection. Here's what I came up with in the 60 seconds I thought it deserved.
Your challenge:
- Do it better. better = faster with same number of items and/or faster with
n
items.
- Prove it.
using System;
using System.Collections.Generic;
static class IEnumerableExtension
{
public static IEnumerable<T> Randomize<T>(this IEnumerable<T> collection)
{
var list = new List<T>(collection);
var randomizer = new Random();
for (int i = list.Count; i > 0; i--)
{
int r = randomizer.Next(0, i);
yield return list[r];
list.RemoveAt(r);
}
}
}
Yvan Rodrigues has 30 years of experience in information systems and software development for the industry. He is Senior Concept Designer at
Robotic Assistance Devices
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, the
University of Waterloo as Information Systems Manager, and
OTTO Motors as Senior Systems Engineer and Senior Concept Designer.
Yvan is currently focused on design of embedded systems.