fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace ConsoleApplication2
  6. {
  7. class Program
  8. {
  9. static void Main(string[] args)
  10. {
  11. var arr = Enumerable.Range(1, 1000).ToArray();
  12.  
  13. for (int i = 0; i < 100; i++)
  14. {
  15. var element = arr.GetRandomSample(1).Single();
  16. Console.WriteLine(element);
  17. }
  18. }
  19. }
  20.  
  21. public static class X
  22. {
  23. private static readonly Random Random = new Random(1);
  24. public static IEnumerable<T> GetRandomSample<T>(this IReadOnlyCollection<T> source, int maxCount)
  25. {
  26. var numbersPicked = 0;
  27. int i = 0;
  28. foreach (var number in source)
  29. {
  30. var prob = (maxCount - numbersPicked) / (double)(source.Count - i);
  31. if (Random.NextDouble() <= prob)
  32. {
  33. yield return number;
  34. numbersPicked++;
  35. }
  36. i++;
  37. }
  38. }
  39. }
  40. }
  41.  
Success #stdin #stdout 0.02s 131840KB
stdin
Standard input is empty
stdout
655
117
194
331
453
697
90
288
937
453
834
217
532
124
846
589
31
670
979
52
73
18
854
184
61
24
158
671
466
883
347
13
264
740
330
322
442
476
936
715
176
993
676
292
933
480
543
217
716
529
541
476
2
422
87
823
813
359
790
720
269
279
620
154
415
32
892
185
664
905
456
784
550
269
664
571
497
255
407
741
435
578
582
694
452
415
706
152
342
801
423
757
998
556
131
596
70
689
913
816