简体   繁体   English

如何将项目添加到C#数组中,以便每个项目恰好具有3个?

[英]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. 我有一个长度为12的int array [],我想用0到3之间的数字随机填充它,但是我想确保数组中正好有0、1、2和3中的三个。 Any ideas on how to do this? 有关如何执行此操作的任何想法?

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;
}

You can start with an ordered array (such as 0,0,0,1,1,1... etc.) and do a shuffle, like shuffling cards. 您可以从有序数组(例如0,0,0,1,1,1 ...等)开始,然后进行洗牌,例如洗牌。 Go through each index and swap the contents with the contents of another random one. 浏览每个索引,然后将内容与另一个随机索引的内容交换。

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 有关详情以及随机排序的更好方法,请参见此处: http : //www.codinghorror.com/blog/2007/12/the-danger-of-naivete.html

Fill the array and then shuffle the numbers. 填充数组,然后重新排列数字。 How to do shuffling you can find here: Randomize a List<T> 如何进行改组,您可以在这里找到: 将List <T>随机化

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

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM