fork download
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. public static class RandomElementSelector
  5. {
  6. public static IList<T> CollectAllowedElements<T>(IList<T> allElements, IList<T> excludedElements)
  7. {
  8. List<T> allowedElements = new List<T>();
  9. foreach (T element in allElements)
  10. if (!excludedElements.Contains(element))
  11. allowedElements.Add(element);
  12. return allowedElements;
  13. }
  14.  
  15. public static T SelectRandomElement<T>(IList<T> allowedElements)
  16. {
  17. Random random = new Random();
  18. int randomIndex = random.Next(allowedElements.Count);
  19. return allowedElements[randomIndex];
  20. }
  21.  
  22. public static T SelectRandomElement<T>(IList<T> allElements, IList<T> excludedElements)
  23. {
  24. IList<T> allowedElements = CollectAllowedElements(allElements, excludedElements);
  25. return SelectRandomElement(allowedElements);
  26. }
  27. }
  28.  
  29. public class Test
  30. {
  31. public static void Main()
  32. {
  33. const int N = 100;
  34.  
  35. // Example #1
  36. int[] allNumbers = new int[N];
  37. for (int i = 0; i < allNumbers.Length; ++i)
  38. allNumbers[i] = i + 1;
  39. int[] excludedNumbers = { 5, 7, 17, 23 };
  40. Console.WriteLine(RandomElementSelector.SelectRandomElement(allNumbers, excludedNumbers));
  41.  
  42. // Example #2
  43. List<string> allStrings = new List<string>();
  44. for (int i = 0; i < N; ++i)
  45. allStrings.Add("Item #" + (i + 1));
  46. string[] excludedStrings = { "Item #5", "Item #7", "Item #17", "Item #23" };
  47. Console.WriteLine(RandomElementSelector.SelectRandomElement(allStrings, excludedStrings));
  48. }
  49. }
Success #stdin #stdout 0.03s 33928KB
stdin
Standard input is empty
stdout
48
Item #21