Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate and repeat number in C#

I want to generate 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?

like image 229
A New Chicken Avatar asked Jan 07 '10 11:01

A New Chicken


People also ask

What does RAND () generate in C?

In the C programming language, the rand() function is a library function that generates the random number in the range [0, RAND_MAX]. When we use the rand() function in a program, we need to implement the stdlib. h header file because rand() function is defined in the stdlib header file.

Can you generate random numbers in C?

The rand() and srand() functions are used to generate random numbers in C/C++ programming languages. The rand() function gives same results on every execution because the srand() value is fixed to 1. If we use time function from time.


1 Answers

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.

like image 60
Jon Skeet Avatar answered Sep 30 '22 04:09

Jon Skeet