当我在宾果板上运行不加倍数字的代码时,Visual Studio 构建成功,但代码未显示在控制台上

问题描述 投票:0回答:1

我创建了一个带有随机数字的宾果板,并且我试图确保宾果板上的数字都不重复。为了做到这一点,我创建了一个方法 CheckDouble()。虽然代码对我来说看起来不错并且没有构建错误,但它没有显示在控制台上。我的代码有意义吗?我可以做些什么来改进它以使其高效构建?

static int[,] card = new int[5, 5];
static Random rand = new Random();
static void PopulateCard()
{
    int num = -1;
    int counter = 0;
    for (int row = 0; row < card.GetLength(0); row++)
    {
        for (int col = 0; col < card.GetLength(1); col++)
        {
            do
            {
                if (row == 2 && col == 2)
                    num = 0;
                else if (col == 0)
                    num = rand.Next(1, 16);
                else if (col == 1)
                    num = rand.Next(16, 31);
                else if (col == 2)
                    num = rand.Next(31, 46);
                else if (col == 3)
                    num = rand.Next(46, 61);
                else
                    num = rand.Next(61, 76);
            }
            while (CheckDouble(counter, num));
            counter++;
            card[row, col] = num;
        }
    }
}
static bool CheckDouble(int num, int counter)
{
    int[] nums = new int[25];
    nums[counter] = num;
    for (int i = 0; i < counter; i++)
    {
        if (nums[i] == num)
            return true;
    }
    return false;
}
c# console
1个回答
0
投票

好吧,你原来的代码有很多问题,但这应该给你你想要的。

static int[,] card = new int[5, 5];
static Random rand = new Random();

public static void PopList()
{
    List<List<int>> cols = new List<List<int>>();
    cols.Add(PopCol(1,15,5));
    cols.Add(PopCol(16,15,5));
    cols.Add(PopCol(31,15,5));
    cols.Add(PopCol(46,15,5));
    cols.Add(PopCol(61,15,5));

    card = PopRows(cols);

    card[2, 2] = 0;
}

public static List<int> PopCol(int min, int increase, int length)
{
    List<int> possibleValues = Enumerable.Range(min, increase).ToList();
    List<int> actualValues = new();

    for (int i = 0; i < length; i++)
    {
        int randIndex = rand.Next(possibleValues.Count);
        int val = possibleValues[randIndex];
        actualValues.Add(val);
        possibleValues.RemoveAt(randIndex);
    }

    return actualValues;

}

public static int[,] PopRows(List<List<int>> cols)
{
    int[,] rows = new int[5, 5];

    for (int i = 0; i < 5; i++)
    {
        for (int j = 0; j < 5; j++)
        {
            rows[j, i] = cols[i][j];
        }
    }
    
    return rows;
}
© www.soinside.com 2019 - 2024. All rights reserved.