using System;
using System.Collections.Generic;
public static class Sorteio {
public static void Main() {
int[] array = { 1, 2, 3, 4 };
array.Shuffle();
foreach (var valor in array) {
Console.WriteLine(valor);
}
Console.WriteLine("Soma: {0}", array[0] + array[2]); // soma 1o. e 3o. elemento
//vamos de novo
array.Shuffle(); //com poucos númros tem chance de repetir
Console.WriteLine("Soma novo sorteio: {0}", array[0] + array[2]); // soma 1o. e 3o. elemento
}
}
namespace System.Collections.Generic {
public static class IListExt {
static Random r = new Random(DateTime.Now.Millisecond);
public static void Shuffle<T>(this IList<T> list, int lowerItem, int upperItem) {
upperItem = upperItem > list.Count ? list.Count : upperItem;
lowerItem = lowerItem < 0 ? 0 : lowerItem;
for (int i = lowerItem; i < upperItem; i++) {
int j = r.Next(i, upperItem);
T tmp = list[j];
list[j] = list[i];
list[i] = tmp;
}
}
public static void Shuffle<T>(this IList<T> list, int upperItem) {
list.Shuffle(0, upperItem);
}
public static void Shuffle<T>(this IList<T> list) {
list.Shuffle(0, list.Count);
}
}
}
dXNpbmcgU3lzdGVtOwp1c2luZyBTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYzsKCnB1YmxpYyBzdGF0aWMgY2xhc3MgU29ydGVpbyB7CiAgICBwdWJsaWMgc3RhdGljIHZvaWQgTWFpbigpIHsKICAgICAgICBpbnRbXSBhcnJheSA9IHsgMSwgMiwgMywgNCB9OwogICAgICAgIGFycmF5LlNodWZmbGUoKTsKICAgICAgICBmb3JlYWNoICh2YXIgdmFsb3IgaW4gYXJyYXkpIHsKICAgICAgICAgICAgQ29uc29sZS5Xcml0ZUxpbmUodmFsb3IpOwogICAgICAgIH0KICAgICAgICBDb25zb2xlLldyaXRlTGluZSgiU29tYTogezB9IiwgYXJyYXlbMF0gKyBhcnJheVsyXSk7IC8vIHNvbWEgMW8uIGUgM28uIGVsZW1lbnRvCiAgICAgICAgLy92YW1vcyBkZSBub3ZvCiAgICAgICAgYXJyYXkuU2h1ZmZsZSgpOyAvL2NvbSBwb3Vjb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gICAgICB9CgogICAgICAgIHB1YmxpYyBzdGF0aWMgdm9pZCBTaHVmZmxlPFQ+KHRoaXMgSUxpc3Q8VD4gbGlzdCkgewogICAgICAgICAgICBsaXN0LlNodWZmbGUoMCwgbGlzdC5Db3VudCk7CiAgICAgICAgfQogICAgfQp9