Arrays.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System.Collections.Generic;
  2. namespace FirstGearGames.Utilities.Objects
  3. {
  4. public static class Arrays
  5. {
  6. /// <summary>
  7. /// Randomizer used for shuffling.
  8. /// </summary>
  9. private static System.Random _random = new System.Random();
  10. /// <summary>
  11. /// Adds an entry to a list if it does not exist already.
  12. /// </summary>
  13. /// <typeparam name="T"></typeparam>
  14. /// <param name=""></param>
  15. /// <param name="value"></param>
  16. public static void AddUnique<T>(this List<T> list, object value)
  17. {
  18. if (!list.Contains((T)value))
  19. list.Add((T)value);
  20. }
  21. /// <summary>
  22. /// Removes an object from a list through re-ordering. This breaks the order of the list for a faster remove.
  23. /// </summary>
  24. /// <typeparam name="T"></typeparam>
  25. /// <param name="list"></param>
  26. /// <param name="value"></param>
  27. /// <returns></returns>
  28. public static bool FastReferenceRemove<T>(this List<T> list, object value)
  29. {
  30. for (int i = 0; i < list.Count; i++)
  31. {
  32. if (object.ReferenceEquals(list[i], value))
  33. {
  34. FastIndexRemove(list, i);
  35. return true;
  36. }
  37. }
  38. return false;
  39. }
  40. /// <summary>
  41. /// Removes an index from a list through re-ordering. This breaks the order of the list for a faster remove.
  42. /// </summary>
  43. /// <typeparam name="T"></typeparam>
  44. /// <param name="list"></param>
  45. /// <param name="index"></param>
  46. public static void FastIndexRemove<T>(this List<T> list, int index)
  47. {
  48. list[index] = list[list.Count - 1];
  49. list.RemoveAt(list.Count - 1);
  50. }
  51. /// <summary>
  52. /// Shuffles an array.
  53. /// </summary>
  54. /// <typeparam name="T"></typeparam>
  55. /// <param name="array"></param>
  56. public static void Shuffle<T>(this T[] array)
  57. {
  58. int n = array.Length;
  59. for (int i = 0; i < (n - 1); i++)
  60. {
  61. int r = i + _random.Next(n - i);
  62. T t = array[r];
  63. array[r] = array[i];
  64. array[i] = t;
  65. }
  66. }
  67. }
  68. }