awesomeguy
awesomeguy

Reputation: 290

How do I add items to a C# array so that I have exactly 3 of each item?

I have an int array[] with a length of 12, and i want to fill it with numbers from 0 to 3 randomly, but i want to make sure that there are exactly three of 0, 1, 2, and 3 in the array. Any ideas on how to do this?

Upvotes: 0

Views: 142

Answers (6)

Jim Mischel
Jim Mischel

Reputation: 134095

Fill it non-randomly and then shuffle:

int[] myArray = new int(12);
for (i = 0; i < 12; ++i)
{
    myArray[i] = i/3;
}

Random rnd = new Random();
for (i = 0; i < 12; ++i)
{
    //int swapWith = rnd.Next(12);
    // Corrected to avoid bias.  See comments.
    int swapWith = rnd.Next(i+1);
    int temp = myArray[i];
    myArray[i] = myArray[swapWith];
    myArray[swapWith] = temp;
}

Upvotes: 5

Rudy
Rudy

Reputation: 895

Here's yet one more way...

        var rnd = new Random();
        var items = Enumerable.Repeat(Enumerable.Range(0, 4), 3).SelectMany(item => item).OrderBy(item => rnd.Next()).ToArray();

Upvotes: 0

Bala R
Bala R

Reputation: 109017

Random rnd=new Random();
var array = new[] {0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3}
                           .OrderBy(i => rnd.Next() )
                           .ToArray();

Upvotes: 0

Robert Levy
Robert Levy

Reputation: 29083

Several of the other answers here suggest simply swapping randomly selected elements. That won't yield truly random results. See here for the details why and a better way of randomly sorting: http://www.codinghorror.com/blog/2007/12/the-danger-of-naivete.html

Upvotes: 1

ChrisWue
ChrisWue

Reputation: 19050

Fill the array and then shuffle the numbers. How to do shuffling you can find here: Randomize a List<T>

Upvotes: 0

AlbeyAmakiir
AlbeyAmakiir

Reputation: 2247

You can start with an ordered array (such as 0,0,0,1,1,1... etc.) and do a shuffle, like shuffling cards. Go through each index and swap the contents with the contents of another random one.

Upvotes: 2

Related Questions