行或列中无3个相同值的随机2D数组

时间:2019-03-18 19:36:26

标签: c#

您好,我们正在寻找一种解决方案,以2-8的随机值填充1D或2行中没有3个相同数字的2D数组。

Random random = new Random();

for (var row = 0; row < RowCount; row++)
{
    for (var column = 0; column < RowCount; column++)
    {
        tiles[row, column] = random.Next(1, 8);
    }
}

1 个答案:

答案 0 :(得分:0)

想法很简单:从右到左,从上到下填充矩阵。为避免在任何单元格出现重复,请向上看两个单元格,再向左看两个单元格,如果它们的值相同,请再次调用random.Next(..)。接下来的代码将创建该矩阵:

// this method checks cells that up to current
private static bool EqualsUp(int i, int j, int[,] matrix, int value) => i >= 0 && matrix[i, j] == value;

// this method checks cells that left to current
private static bool EqualsLeft(int i, int j, int[,] matrix, int value) => j >= 0 && matrix[i, j] == value;

public static int[,] GenerateMatrix(int h, int w)
{
    var matrix = new int[h, w];
    var random = new Random();

    for (var i = 0; i < h; ++i)
    for (var j = 0; j < w; ++j)
        while (true)
        {
            var cellValue = random.Next(1, 9); // note: second value is exclusive, so to generate values from 1 to 8 pass 9 as second argument
            if (EqualsUp(i - 1, j, matrix, cellValue) && EqualsUp(i - 2, j, matrix, cellValue))
                continue; // need to regenerate cellValue
            if (EqualsLeft(i, j - 1, matrix, cellValue) && EqualsLeft(i, j - 2, matrix, cellValue))
                continue; // need to regenerate cellValue

            matrix[i, j] = cellValue;
            break;
        }

    return matrix;
}