Search code examples
c#repeatenumerable

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?


Solution

  • 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.