检查2D数组c#sharp中的某些元素是否相等

检查2D数组c#sharp中的某些元素是否相等,c#,arrays,string,for-loop,methods,C#,Arrays,String,For Loop,Methods,给定阵列: 字符串[,]arr=新字符串[n,n]。 如何检查每行、每列和两条对角线的元素是否相等 这是一种tic-tac-toe:编写一个控制台应用程序,将X和0的N个移动作为坐标接收作为输入日期。(0,0)是左上角,(2,2)是右下角。第一行是移动的次数N,第二行有移动,每行一个。第一步是玩家移动X,然后是玩家移动0,然后再次移动X,依此类推。应用程序将分析收到的移动,并显示赢家:X,0或平局,如果没有赢家。 这是我尝试过的,但没有结果: static void Main() {

给定阵列:

字符串[,]arr=新字符串[n,n]。 如何检查每行、每列和两条对角线的元素是否相等

这是一种tic-tac-toe:编写一个控制台应用程序,将X和0的N个移动作为坐标接收作为输入日期。(0,0)是左上角,(2,2)是右下角。第一行是移动的次数N,第二行有移动,每行一个。第一步是玩家移动X,然后是玩家移动0,然后再次移动X,依此类推。应用程序将分析收到的移动,并显示赢家:X,0或平局,如果没有赢家。 这是我尝试过的,但没有结果:

static void Main()
    {
        int numberOfMoves = Convert.ToInt32(Console.ReadLine());
        const int size = 3;
        string[,] boardGame = new string[size, size];
        for (int i = 0; i < numberOfMoves; i++)
        {
            string strCoordinates = Console.ReadLine();
            string[] lineCoordinates = strCoordinates.Split(' ');
            int coordinateX = Convert.ToInt32(lineCoordinates[0]);
            int coordinateY = Convert.ToInt32(lineCoordinates[1]);
            const int value = 2;
            boardGame[coordinateX, coordinateY] = i % value == 0 ? "X" : "0";
        }

        // CheckElements(boardGame); in construction
        Console.Read();
    }

    static void CheckRows(int x, int y)
    {
        string[,] boardGame = new string[3, 3];
        int cols = boardGame.GetLength(1);
        const int value = 2;
        for (int i = 0; i < cols; i++)
        {
            if ((boardGame[0, 0] == boardGame[0, 1] && boardGame[0, 1] == boardGame[0, value]) || (boardGame[1, 0] == boardGame[1, 1] && boardGame[1, 1] == boardGame[1, value]))
            {
                Console.WriteLine(boardGame[0, 0]);
            }

            if ((boardGame[1, 0] == boardGame[1, 1] && boardGame[1, 1] == boardGame[1, value]) || (boardGame[value, 0] == boardGame[value, 1] && boardGame[value, 1] == boardGame[value, value]))
            {
                Console.Write(boardGame[0, 0]);
            }
        }

        Console.WriteLine(boardGame[x, y]);
    }

    static void CheckColumns(int x, int y)
    {
        string[,] boardGame = new string[3, 3];
        int rows = boardGame.GetLength(0);
        const int value = 2;
        for (int i = 0; i < rows; i++)
        {
            if ((boardGame[0, 0] == boardGame[1, 0] && boardGame[1, 0] == boardGame[value, 0]) || (boardGame[0, 1] == boardGame[1, 1] && boardGame[1, 1] == boardGame[value, 1]))
            {
                Console.WriteLine(boardGame[0, 0]);
            }

            if ((boardGame[0, 1] == boardGame[1, 1] && boardGame[1, 1] == boardGame[value, 1]) || (boardGame[0, value] == boardGame[1, value] && boardGame[1, value] == boardGame[value, value]))
            {
                Console.WriteLine(boardGame[0, 1]);
            }
        }

        Console.WriteLine(boardGame[x, y]);
    }

    static void CheckDiagonals(int x, int y)
    {
        string[,] boardGame = new string[3, 3];
        int m = boardGame.Length;
        const int value = 2;
        for (int i = 0; i < m; i++)
        {
            m--;
            for (int j = 0; j < m; j++)
            {
                if (boardGame[0, 0] == boardGame[1, 1] && boardGame[1, 1] == boardGame[value, value])
                {
                    Console.WriteLine(boardGame[0, 0]);
                }
            }
        }

        Console.WriteLine(boardGame[x, y]);
    }
static void Main()
{
int numberOfMoves=Convert.ToInt32(Console.ReadLine());
常数int size=3;
字符串[,]boardGame=新字符串[大小,大小];
for(int i=0;i
这显然是家庭作业,所以我不打算为您做这件事,但我会浏览您的代码,并在我认为有问题的地方以及需要如何更改的地方发表评论:

    //i think this method should take the game board as a parameter, not x and y
    //because your game oard is populated in the main as a variable that is not accessible anywhere
    //outside the main
    static void CheckRows(int x, int y)
    {
        //this should be an input parameter, rather than being declared here
        string[,] boardGame = new string[3, 3];
   
        //ok this gets the number of columns..
        int cols = boardGame.GetLength(1);

        //..but where is the same thing for rows? I know it's a square board but
        //it's easy to code up the rows too, for ultimate flexibility

        //what's this for? looks like you're limiting yourself to 3x3 boards?
        const int value = 2;

        //i'd have probably called this variable col, or c
        //and I'd probably start it at 1...
        for (int i = 0; i < cols; i++)
        {
            //you declared i but you don't use it? You have a loop that increments
            //a number through 0, 1, 2, 3 ... just like you've hard coded here
            //so think about what you hardcoded and how you could do that in a loop
            // - see later for a hint

            if ((boardGame[0, 0] == boardGame[0, 1] && boardGame[0, 1] == boardGame[0, value]) || (boardGame[1, 0] == boardGame[1, 1] && boardGame[1, 1] == boardGame[1, value]))
            {
                Console.WriteLine(boardGame[0, 0]);
            }

            //ok, so now you've moved onto hard coding row number 1, and hard coding
            //a bunch of columns.. think about how you could use the variables you have
            if ((boardGame[1, 0] == boardGame[1, 1] && boardGame[1, 1] == boardGame[1, value]) || (boardGame[value, 0] == boardGame[value, 1] && boardGame[value, 1] == boardGame[value, value]))
            {
                Console.Write(boardGame[0, 0]);
            }
        }

        //what is this for?
        Console.WriteLine(boardGame[x, y]);
    }

我们所做的就是把维度作为硬编码的东西添加进去。。。第0行。列c是一个变量

但是如果我们想让它成为一个变量,那么我们检查所有的维度呢

使用两个循环

for(int r = 0; r < nums.GetLength(0); r++){ //rows start from 0!

  int first = nums[r, 0]; //row is variable, column is first
  for(int c = 1; c < nums.GetLength(1); c++){ //cols start from 1!

    if(nums[r, c] == first) //r will be 0, while c goes 1..3, then r will be 1 while c is 1..3 etc
这意味着您只能使用一个变量,因为数字重复:

for(int i = 0; i < ... )

  if(x{0,0] == x[i,i])
for(int i=0;i<…)
如果(x{0,0]==x[i,i])

祝你好运!

给定一个方阵,有一种方法可以在一个循环中执行所有检查。 但在进行优化之前,让我们先进行清理和简化

考虑到下面的平方矩阵,可能很难进行所有的交换来找到赢家

var input = new [,]{
    {"x","x","x"},
    {"x","x","o"},
    {"x","o","o"},
};
但如果我们能够将其切成行、列和对角线。 如果给定
{“x”、“x”、“x”}、
{“x”、“x”、“o”}
,将更容易找到获胜者

static string[] GetRow(string[,] source, int rowNumber)
{
    var rows = source.GetLength(0);
    var result = new string[rows];
    for (int i = 0; i < rows; i++)
    {
        result[i] = source[rowNumber, i];
    }
    return result;
}
行/列 根据您之前的问题B,您已经知道,在2D数组中,我们可以使用
GetLength(1)
GetLength(0)
来计算列数和行数

对于本例,第一行索引为:
{(0,0)、(0,1)、(0,2)}

static string[] GetRow(string[,] source, int rowNumber)
{
    var rows = source.GetLength(0);
    var result = new string[rows];
    for (int i = 0; i < rows; i++)
    {
        result[i] = source[rowNumber, i];
    }
    return result;
}
对于反对角线索引,将是
{(0,2)、(1,1)、(2,0)}

行从0>1>2递增。
而列则相反。2>1>0

static string[] GetSquareMatrixAntiDiagonal(string[,] source)
{
    var cols = source.GetLength(0);
    var rows = source.GetLength(1);
    if (cols != rows) throw new ArgumentException($"2D Array [{rows},{cols}], is not a Square matrix");

    var result = new string[rows];
    var row = 0;
    var col = rows - 1;
    for (int i = 0; i < rows; i++)
    {
        result[i] = source[row++, col--];
    }
    return result;
}
小心这将返回空值作为
{“”,“”}
上的赢家。 但是我们可以在最后的检查中排除这个

这是另一个没有LinQ的版本,并且没有正确处理空字符串和空单元格的默认值。 免责声明:此方法中使用的有效符号与小提琴输入不匹配

如果您将“行数或列数”重命名为大小。在检查它是否为方形矩阵后。 每个方法都可能处于同一个循环中。让我们尝试合并
GetRow
GetColumn
以说明:对于第一行和第一列,使用
col\u row\u index=0;

var size = source.GetLength(0);

var currentColumn = new string[size]; // old result variable
var currentRow = new string[size];    // old result variable

for (int i = 0; i < size; i++)
{
    currentColumn[i] = source[i, col_row_index];
    currentRow[i] = source[col_row_index, i];
}


我允许您对对角线进行合并。您应该能够进行整个棋盘检查,只需稍加修改。

您的示例中没有包含
CheckElements(string[,]boardGame)
函数。@Creyke,是的,我没有编写CheckElements b函数
static string[] GetColumn<T>(string[,] source, int columnNumber)
{
    var cols = source.GetLength(1);
    var result = new string[cols];
    for (int i = 0; i < cols; i++)
    {
        result[i] = source[i, columnNumber];
    }
    return result;
}
string[] GetSquareMatrixMainDiagonal(string[,] source)
{// {(0,0) , (1,1), (2,2)}

    var cols = source.GetLength(0);
    var rows = source.GetLength(1);
    if (cols != rows) // diagonal will not work on not square matrix.
        throw new ArgumentException($"2D Array [{rows},{cols}], is not a Square matrix");

    var result = new string[rows];
    for (int i = 0; i < rows; i++)
    {
        result[i] = source[i, i];
    }
    return result;
}
static string[] GetSquareMatrixAntiDiagonal(string[,] source)
{
    var cols = source.GetLength(0);
    var rows = source.GetLength(1);
    if (cols != rows) throw new ArgumentException($"2D Array [{rows},{cols}], is not a Square matrix");

    var result = new string[rows];
    var row = 0;
    var col = rows - 1;
    for (int i = 0; i < rows; i++)
    {
        result[i] = source[row++, col--];
    }
    return result;
}
static string Winner(string[] source)
{
    var val = source.First();
    var isTheSame = source.Skip(1).All(x => x == val);
    return isTheSame ? val : default(string);
}    
static bool CheckWinner(string[] source, out string winnerSymbol)
{
    winnerSymbol= "-"; // "-", arbitrary representation of an empty cell. 1 char for simple layout.
    
    var firstVal = source[0];
    for(int i = 1; i < source.Length; i++){ 
        if(source[i] != firstVal){
            return false;
        }
    }
    
    // Will be nice to have valid Symbols in an array.
    if(firstVal!= "0" && firstVal != "X"){      
        return false;
    }
    
    winnerSymbol = firstVal;
    return true;
}

static void ExampleUsageOf_CheckWinner(){
    var winInput= new []{"0","0","0"};  
    var looseInput= new []{"0","0","X"};


    if(CheckWinner(winInput, out string winnerSymbol)){
        Console.WriteLine( winnerSymbol +"is a Winner in winInput")
    }
    else{
        Console.WriteLine( "No winner in winInput!")
    }
    
    
    if(CheckWinner(looseInput, out string winnerSymbol)){
        Console.WriteLine( winnerSymbol +"is a Winner in looseInput")
    }
    else{
        Console.WriteLine( "No winner in looseInput!")
    }
} 
var r1 = GetRow(input, 0);
var r2 = GetRow(input, 1);
var r3 = GetRow(input, 2);
var size = source.GetLength(0);

var currentColumn = new string[size]; // old result variable
var currentRow = new string[size];    // old result variable

for (int i = 0; i < size; i++)
{
    currentColumn[i] = source[i, col_row_index];
    currentRow[i] = source[col_row_index, i];
}
var winnerC = Winner(currentColumn);
var winnerR = Winner(currentColumn);

if(winnerC != ""){
    // Stop everything! We have a winner 
    // Console.WriteLine + Break, if we are in a loop.
    // Set a boolean to true, if we use some State machine.
    // Return if we are in method
}

if(winnerR != ""){ // Same
}