예제 #1
0
        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)));
        }
예제 #2
0
 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);
     }
 }