C# appointing distinct array elements randomly to another array

So your problem, freely translated is:

I have a sequential, numeric array containing values from 1 through 30. I want to select 6 unique values from this array from random positions.

The accepted solution to this is to properly (e.g. Fisher-Yates) shuffle the array and simply take the number of required elements from the front.

Given you may want to keep your original array in order, you could create a copy and shuffle that.

That’ll look like this:

var sourceArray = // your loop, or something like Enumerable.Range(1, 30).ToArray();
var arrayToPickFrom = Shuffle(sourceArray.ToArray()); // make a copy and shuffle it
var randomCards = arrayToPickFrom.Take(6); // take the first six elements 

Alternatively, the question could be simplified:

I want to generate N random, unique numbers between 1 and M.

Which is even less lines of code. But it all depends on your requirements. If you’re actually trying to create a card game, where after the initial six cards more cards will be drawn – and a card can only be drawn once, you should approach this problem entirely different, for starters by introducing a Deck class to contain all cards, having convenient methods…

Browse More Popular Posts

Leave a Comment