public static T RandomOrDefault <T>(this IEnumerable <T> things, Battleship.ShuggyCoUk.Simple.Rand rand) { int count = things.Count(); if (count == 0) { return(default(T)); } return(things.ElementAt(rand.Next(count))); }
public static IEnumerable <T> Shuffle <T>(this IEnumerable <T> source, Battleship.ShuggyCoUk.Simple.Rand rand) { T[] elements = source.ToArray(); // Note i > 0 to avoid final pointless iteration for (int i = elements.Length - 1; i > 0; i--) { // Swap element "i" with a random earlier element it (or itself) int swapIndex = rand.Next(i + 1); T tmp = elements[i]; elements[i] = elements[swapIndex]; elements[swapIndex] = tmp; } // Lazily yield (avoiding aliasing issues etc) foreach (T element in elements) { yield return(element); } }