ShuffleBag.cs 1019 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System;
  2. using System.Collections.Generic;
  3. /// <summary>
  4. /// Shuffle bag based off http://gamedev.tutsplus.com/tutorials/implementation/shuffle-bags-making-random-feel-more-random/
  5. /// </summary>
  6. public class ShuffleBag<T>
  7. {
  8. private Random random = new Random();
  9. private List<T> data;
  10. private T currentItem;
  11. private int currentPosition = -1;
  12. private int Capacity { get { return data.Capacity; } }
  13. public int Size { get { return data.Count; } }
  14. public ShuffleBag(int initCapacity)
  15. {
  16. data = new List<T>(initCapacity);
  17. }
  18. public void Add(T item, int amount = 1)
  19. {
  20. for (int i = 0; i < amount; i++)
  21. {
  22. data.Add(item);
  23. }
  24. currentPosition = Size - 1;
  25. }
  26. public T Next()
  27. {
  28. if (currentPosition < 1)
  29. {
  30. currentPosition = Size - 1;
  31. currentItem = data[0];
  32. return currentItem;
  33. }
  34. var pos = random.Next(currentPosition);
  35. currentItem = data[pos];
  36. data[pos] = data[currentPosition];
  37. data[currentPosition] = currentItem;
  38. currentPosition--;
  39. return currentItem;
  40. }
  41. }