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