简体   繁体   English

如何检查数组中的多个值是否等于一个字符串?

[英]How to check if multiple values in an array are equal to one string?

So I am making a X and O's game as a little project for myself while I learn C# and was wondering how I can check certain values in an array are equal to one string. 因此,当我学习C#时,我正在自己做一个X和O游戏,作为一个小项目,想知道如何检查数组中的某些值等于一个字符串。

So I store all the values on my grid in an array called gridValues[] and I am creating a method to check if someone has one after a go. 因此,我将所有值存储在名为gridValues[]的数组中的网格上,并且正在创建一种方法来检查某人是否在旅途中是否拥有一个。 So how do I check if lets say gridValues[0] , gridValues[1] and gridValues[2] (the top row) are all equal to 'X'. 因此,如何检查是否让gridValues[0]gridValues[1]gridValues[2] (第一行)都等于'X'。

Also is there any simpler way to check all the combinations? 还有没有更简单的方法来检查所有组合?

I prefer this one 我喜欢这个

    {
        if(
            IsEqual(gridValues, 0,1,2) || 
            IsEqual(gridValues, 3,4,5) || 
            IsEqual(gridValues, 6,7,8) ||
            IsEqual(gridValues, 0,4,8) || 
            IsEqual(gridValues, 6,4,2) || 
            IsEqual(gridValues, 0,3,6) || 
            IsEqual(gridValues, 1,4,7) || 
            IsEqual(gridValues, 2,5,8) )
            {
                /* is done */
            }
            else
            {
                /* not equal */
            }
    }

    public static bool IsEqual(string[] A,params int[] index)
    {
        if(index.Length==0)
            return false;
        for(int i=1;i<index.Length;i++)
            if(A[index[i]]!=A[0])
                return false;
        return true;
    }   

And this maybe exact code you are looking for 这可能是您正在寻找的确切代码

    public static bool IsDone(string[] gridValues, string O_X)
    {
        if (
            IsEqual(gridValues, O_X, 0, 1, 2) ||
            IsEqual(gridValues, O_X, 3, 4, 5) ||
            IsEqual(gridValues, O_X, 6, 7, 8) ||
            IsEqual(gridValues, O_X, 0, 4, 8) ||
            IsEqual(gridValues, O_X, 6, 4, 2) ||
            IsEqual(gridValues, O_X, 0, 3, 6) ||
            IsEqual(gridValues, O_X, 1, 4, 7) ||
            IsEqual(gridValues, O_X, 2, 5, 8))
            return true;
        return false;
    }

    public static bool IsEqual(string[] A, string a, params int[] index)
    { 
        for (int i = 0; i < index.Length; i++)
            if (A[index[i]] != a)
                return false;
        return true;
    } 

You can use it like this: IsDone(gridValues, 'X') 您可以像这样使用它: IsDone(gridValues, 'X')

Storing your grid values in a 3x3 2D array might be an easier way to go to if you are trying to check if there are three of one type in a row. 如果要检查一行中是否存在三种类型的网格,将网格值存储在3x3 2D数组中可能是一种更简单的方法。 The 2D array will let you iterate through your grid a little easier. 2D数组使您可以更轻松地遍历网格。

I recommend something like this. 我推荐这样的东西。 First, we define the different winning combinations for the array. 首先,我们为阵列定义不同的获胜组合。 Next we go through each of the index sets (the winning combinations), getting the elements they represent as an array. 接下来,我们遍历每个索引集(获胜组合),获取它们表示为数组的元素。 Next, we check that the first item isn't null or an empty string (ie it's a played item), and then we check that they all match. 接下来,我们检查第一个项目不是null还是一个空字符串(即它是一个播放的项目),然后我们检查它们是否都匹配。 If there's a match, it's a winning play and we return. 如果有比赛,那是一场胜利,我们返回。 Otherwise, it's a losing play so we try the next set. 否则,这是一场失败的比赛,因此我们尝试下一组。 If that fails, we return null. 如果失败,则返回null。

This will be more efficient than checking X and O individually, since we're simply looking for 3 in a row. 这将比单独检查X和O更有效,因为我们只是连续查找3。 The key part to excluding unplayed tiles is !string.IsNullOrEmpty(elements[0]) . 排除未播放的图块的关键部分是!string.IsNullOrEmpty(elements[0])

private static string GetWinner(string[] grid)
{
    var indexSets = new []
    {
        // Horizontal
        new [] { 0, 1, 2 },
        new [] { 3, 4, 5 },
        new [] { 6, 7, 8 },

        // Vertical
        new [] { 0, 3, 6 },
        new [] { 1, 4, 7 },
        new [] { 2, 5, 8 },

        // Diagonal
        new [] { 0, 4, 8 },
        new [] { 6, 4, 2 }
    };

    foreach (var indices in indexSets)
    {
        var elements = indices.Select(i => grid[i]).ToArray();
        if (!string.IsNullOrEmpty(elements[0]) && elements[0] == elements[1] && elements[0] == elements[2])
        {
            return elements[0];
        }
    }

    return null;
}

Usage example: 用法示例:

public static void Main(string[] args)
{
    var testSet = new string[]
    {
        "X", "O", "O",
        "O", "X", "O",
        "O", "X", "X"
    };
    var winner = GetWinner(testSet);
    if (winner != null)
    {
        Console.WriteLine($"{winner} wins!");
    }
}

Try it online 在线尝试

To compare three array elements to a given value, it can be done a number of ways, but probably the most straightforward method would be to simply build binary truth statement and put that in an if statement: 为了将三个数组元素与给定值进行比较,可以通过多种方法来完成,但是最直接的方法可能是简单地构建二进制真值语句并将其放入if语句中:

if (gridValues[0] == 'X' && gridValues[1] == gridValues[0] && gridValues[2] == gridValues[0])
{
    /* do something */
}
else
{
    /* do something else */
}

That said, I don't think I would use this method to solve your overall issue of trying to find three 'X's in a row in a 3 x 3 grid. 就是说,我认为我不会使用这种方法来解决您试图在3 x 3的网格中连续查找三个'X'的整体问题。

If they are the only values in you array ( I mean if the array contains just those values to compare ) 如果它们是数组中唯一的值(我的意思是如果数组仅包含要比较的值)

You can do it in linq in one line ! 您可以在linq中一行完成它!

Here is an example : 这是一个例子:

string[] arr = { "X", "X", "X" };
var test = arr.All(x => x == "X");
Console.WriteLine(test); // Will return true if all of them is X

Else you can loop for gettings the first values : 另外,您可以循环获取第一个值:

for(int i=0;i<3;i++){
if(gridValues[i] != "X")
  {
    Console.WriteLine("Not equls");
    break;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM