开发者

Generate and repeat number in C#

开发者 https://www.devze.com 2022-12-15 13:53 出处:网络
I want to gene开发者_如何转开发rate an array that has 144 number from 1->36 in random order (so each number is repeated 4 times). Can we use Enumerable.Repeat and Enumerable.Range to do that. If yes t

I want to gene开发者_如何转开发rate an array that has 144 number from 1->36 in random order (so each number is repeated 4 times). Can we use Enumerable.Repeat and Enumerable.Range to do that. If yes than please explain to me how?


Well, creating the sequence with all the numbers in is easy:

var items = from x in Enumerable.Range(1, 36)
            from y in Enumerable.Repeat(x, 4)
            select y;

Then you can just use ToArray to get it into an array and shuffle it. There are numerous questions about shuffling an array in C# on SO, such as this one. You could either use that code directly, or call ToArray and shuffle the array in place without yielding it at the end.


int[] numbers = Enumerable.Range(0, 144).Select(i => (i % 36)+1).OrderBy(g => Guid.NewGuid()).ToArray();


// Generate the list (not in random order)
var one_to_36 = Enumerable.Range(1, 36);
var lst = one_to_36.Concat(one_to_36).Concat(one_to_36).Concat(one_to_36).ToList();

// Randomize the list by swapping random elements
Random rnd = new Random();
for(int i = 0; i < lst.Count; i++)
{
    int i1 = rnd.Next(lst.Count);
    int i2 = rnd.Next(lst.Count);
    int tmp = lst[i1];
    lst[i1] = lst[i2];
    lst[i2] = tmp;
}


var seq = Enumerable.Range(0, 144);    
var all = seq.ToList();
var random = new Random();
var result = seq.Select(i => {
 var index = random.Next()%all.Count;
 var r = all[index] % 36 + 1; all.RemoveAt(index);
 return r;
}).ToList();
0

精彩评论

暂无评论...
验证码 换一张
取 消