随机化数组列表

时间:2014-08-24 19:06:06

标签: c# collections arraylist shuffle

我正在尝试制作一个输出6个唯一随机数的loto数字生成器程序。 我之前使用collections.shuffle方法使用java。我在c#中找不到这样的方法。我看到的唯一方法是随机方法。我试图在我的代码中使用此方法,但它不会产生唯一的随机数。有时在我的loto号码程序中产生重复数字。我已经在这里放了一份我的代码供你查看,并为你评论过,这样你就可以看到我想要做的事了。感谢。

    static void Main(string[] args)
    {
        Random number = new Random();// object to randomize the arraylist ,LIST.
        ArrayList list = new ArrayList();
        for (int i = 1; i <= 49; i++) // Loop to populate the arraylist with int values from 1 to 49.
        {
            list.Add(i);
            Console.WriteLine(number.Next(i)); // Output the contents of the arraylist in a randome order. (This produces duplicat numbers.
            // I am trying to produce a loto number generator program. No duplicat numbers. Each random number must be unique.
        }
        for (int i = 1; i <= 6; i++)// This loop was going to be used to trip the ammount of random numbers displayed.
        {

2 个答案:

答案 0 :(得分:-1)

您可以使用Fisher-Yates混洗算法和随机数生成器对数组进行随机播放:

static void Shuffle(ref ArrayList list)
{
    Random rng = new Random();

    for (int i = list.Count - 1; i >= 0; i--)
    {
        // Note: It's important to only select a number into each index
        // once. Otherwise you'll get bias toward some numbers over others.
        int number = rng.Next(i); // Choose an index to swap here
        Swap(ref list[i], ref list[number]) // Swap it
    }
}

static void Swap(ref int first, ref int second)
{
    int temp = first;
    first = second;
    second = temp;
}

static void Main(string[] args)
{
    ArrayList list = new ArrayList();
    for(int i = 1; i <= 49; i++)
    {
        list.Add(i);
    }
    Shuffle(ref list);

    for (int i = 1; i <= 6; i++)
    {
        // Use the shuffled list
    }
}

如果您只想选择六个唯一的随机数,则不需要随机播放数组。您可以跟踪以前生成的数字,并在重复时重新生成下一个数字。

static ArrayList GetUniqueRandomNumbers(int min, int max, int count)
{
    Random rng = new Random();
    ArrayList result = new ArrayList();

    while(ArrayList.Count < count)
    {
        int number = rng.Next(min, max);

        // Only add if it hasn't been generated yet
        if (!result.Contains(number))
        {
            result.Add(number);
        }
    }
}

static void Main(string[] args)
{
    ArrayList loto = GetUniqueRandomNumbers(1, 49, 6);

    for (int i = 1; i <= 6; i++)
    {
        // Use the generated numbers
    }
}

答案 1 :(得分:-2)

检查ArrayList中是否包含随机数

    var rnd = new Random();

    var list = new ArrayList();

    while (list.Count <= 6)
    {
        int t = rnd.Next(1, 49);
        while (list.Contains(t))
        {
            t = rnd.Next(1, 49);
        }

        list.Add(t);
    }