code_junkie

Ensure uniform (ish) distribution with random number generation

Nov 14th, 2011
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. static IEnumerable<T> GetItems<T>(IEnumerable<Queue<T>> queues)
  2. {
  3. int remaining = queues.Sum(q => q.Count);
  4. Random rand = new Random();
  5. while (remaining > 0)
  6. {
  7. int index = rand.Next(remaining);
  8. foreach (Queue<T> q in queues)
  9. {
  10. if (index < q.Count)
  11. {
  12. yield return q.Dequeue();
  13. remaining--;
  14. break;
  15. }
  16. else
  17. {
  18. index -= q.Count;
  19. }
  20. }
  21. }
  22. }
  23.  
  24. int remaining = 0;
  25. foreach(Queue<T> q in queues) {remaining += q.Count;}
  26.  
  27. static void Main()
  28. {
  29. List<Queue<int>> queues = new List<Queue<int>> {
  30. Build(1,2,3,4,5), Build(6,7,8), Build(9,10,11,12,13)
  31. };
  32. foreach (int i in GetItems(queues))
  33. {
  34. Console.WriteLine(i);
  35. }
  36. }
  37. static Queue<T> Build<T>(params T[] items)
  38. {
  39. Queue<T> queue = new Queue<T>();
  40. foreach (T item in items)
  41. {
  42. queue.Enqueue(item);
  43. }
  44. return queue;
  45. }
  46.  
  47. private Random random = new Random();
  48. public int RandomSort(Queue q1, Queue q2)
  49. {
  50. if (q1 == q2) { return 0; }
  51. return random.Next().CompareTo(random.Next());
  52. }
Add Comment
Please, Sign In to add comment