fork download
  1. using static System.Console;
  2. using System.Collections.Generic;
  3.  
  4. public static class Sorteio {
  5. public static void Main() {
  6. int[] array = { 1, 2, 3, 4 };
  7. array.Shuffle();
  8. foreach (var valor in array) WriteLine(valor);
  9. WriteLine("Soma: {0}", array[0] + array[2]); // soma 1o. e 3o. elemento
  10. //vamos de novo
  11. array.Shuffle(); //com poucos númros tem chance de repetir
  12. WriteLine($"Soma novo sorteio: {array[0] + array[2]}"); // soma 1o. e 3o. elemento
  13. }
  14. }
  15.  
  16. namespace System.Collections.Generic {
  17. public static class IListExt {
  18. static Random r = new Random(DateTime.Now.Millisecond);
  19.  
  20. public static void Shuffle<T>(this IList<T> list, int lowerItem, int upperItem) {
  21. upperItem = upperItem > list.Count ? list.Count : upperItem;
  22. lowerItem = lowerItem < 0 ? 0 : lowerItem;
  23. for (int i = lowerItem; i < upperItem; i++) {
  24. int j = r.Next(i, upperItem);
  25. T tmp = list[j];
  26. list[j] = list[i];
  27. list[i] = tmp;
  28. }
  29. }
  30.  
  31. public static void Shuffle<T>(this IList<T> list, int upperItem) => list.Shuffle(0, upperItem);
  32.  
  33. public static void Shuffle<T>(this IList<T> list) => list.Shuffle(0, list.Count);
  34. }
  35. }
Success #stdin #stdout 0.03s 17740KB
stdin
Standard input is empty
stdout
4
2
1
3
Soma: 5
Soma novo sorteio: 6