随机分配数组值和另一个数组的值

时间:2018-11-23 01:26:24

标签: c# arrays list random

如何为一组数组值分配另一个数组值?两者都有26个值。

我正在模拟一个Deal或No Deal游戏,其中用户从指定的列表中选择一个案例。现在,在控制台应用程序的每次运行中,我希望对每种情况的每个现金奖励都有一个随机分配(出于公平考虑)。我的代码如下:

    int[] cashPrizeArray = new int[] { 0, 1, 2, 5, 10, 20, 50, 100, 150, 200, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 10000, 15000, 20000, 25000, 50000, 75000, 100000, 200000 };
    string[] caseArray = new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26" };

    Console.WriteLine("Deal or Not!");
    Console.Write("Choose a case: 1-26: ");
    string userCase = Console.ReadLine();



    if (!caseArray.Contains(userCase))
    {
        Console.WriteLine("\nUnexpected input text.\nThis application will now be terminated.\nPress ENTER to continue...");
        Console.ReadLine();
        Environment.Exit(0);
    }

    else
    {
        Console.WriteLine("You chose case " + userCase);
        Console.ReadLine();
    }

当用户选择它们时,我需要一一引用它们,然后在最初打开它们时将它们从数组中删除。

1 个答案:

答案 0 :(得分:0)

如果您创建2D列表,其中第一个维度显示的是哪种情况,第二个维度显示的是该金额的金额。然后检查您是否已经拥有 使用了该特定情况,如果是,则再试一次(使用goto,但您可以更改),或者如果尚未使用,则将该情况与第二维中的钱一起添加到列表中。

代码:

public static List<List<string>> PairedCases = new List<List<string>>();

    public static void addsubstrin(string money, string casenom)
    {
        List<string> sublist = new List<string>();

        sublist.Add(money);
        sublist.Add(casenom);

        PairedCases.Add(sublist);
    }

    static void Main(string[] args)
    {
        int[] cashPrizeArray = new int[] { 0, 1, 2, 5, 10, 20, 50, 100, 150, 200, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 10000, 15000, 20000, 25000, 50000, 75000, 100000, 200000 };
        string[] caseArray = new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26" };

        Random rnd = new Random();

        foreach (int inte in cashPrizeArray)
        {
            Restart:;

            int putincase = rnd.Next(1, 27);

            bool found = false;

            //here we chack if its already in the list

            for (int a = 0; a < PairedCases.Count(); a++)
            {
                if (putincase.ToString() == PairedCases[a][1])
                {
                    found = true;
                }
            }

            if(found == false)
            {
                addsubstrin(inte.ToString(), putincase.ToString());
            }
            else
            {
                goto Restart;
            }
        }

        for (int i = 0; i < PairedCases.Count(); i++)
        {
            Console.WriteLine(PairedCases[i][0] + "   " + PairedCases[i][1]);
        }

        Console.ReadLine();
    }