0

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.

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. So how do I check if lets say gridValues[0], gridValues[1] and gridValues[2] (the top row) are all equal to 'X'.

Also is there any simpler way to check all the combinations?

5
  • 1
    I've removed your visual-studio tag for you. It is only meant for tags relating to issues with Visual Studio itself, not code that was written in Visual Studio. Common tags have usage descriptions (see tagging for more info) in order to help you decide if they fit your question or not. Commented Jun 15, 2018 at 13:54
  • 2
    Can you show how you define your array? Is it 1d, 2d or jagged? Commented Jun 15, 2018 at 13:57
  • the array is 1d. Commented Jun 15, 2018 at 13:59
  • So can I assume that 0-2 represents the first horizontal row, 3-5 the second, and 6-8 the third? Commented Jun 15, 2018 at 14:03
  • yes that is correct.but remember you also have to check vertical and diagonal. Commented Jun 15, 2018 at 14:04

5 Answers 5

2

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. The 2D array will let you iterate through your grid a little easier.

Sign up to request clarification or add additional context in comments.

2 Comments

i was thinking of trying that later but at the moments im just getting the basics of the game in place. also diagonals might be harder with a 2d array.
Diagonals are easier with a 2d array.
2

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')

2 Comments

this looks good and clean but i dont like using stuff that i dont understand especially while im learning, so could you explain what the IsEqual method does?
It simply checks if the items with given indices in array A are equal or not
0

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 (i.e. it's a played item), and then we check that they all match. 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.

This will be more efficient than checking X and O individually, since we're simply looking for 3 in a row. The key part to excluding unplayed tiles is !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

Comments

0

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 (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.

5 Comments

isn't it more clean to use for loop ?
I was trying to answer the direct question, "So how do I check if lets say gridValues[0], gridValues[1] and gridValues[2] (the top row) are all equal to 'X'?"
See my answer though :)
I did. I wouldn't think that comparing three variables to a fixed value in a loop is more efficient than the if statement above.
While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
-2

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 !

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;
  }
}

5 Comments

@john Well , I'm not designing his game, I'm answering his specific question about comparing three values in an array with a specific string, Wasn't that his question?
But you're not comparing 3 values in an array, you're comparing all values in an array. And with your second example, what happens if the values he wants to compare aren't next to each other?
I said for the first linq code : if he has only the three elements he wanted in his array , then use linq, otherwise : I wrote the for loop :) so I give him both ways and he could take what he needs because he also didn't specify the array length :) EDIT : after your edited comment : he asked to compare the three with X , so if any of them not true, will break and that's what he asked about :) I'm I right ?
He also said: "Also is there any simpler way to check all the combinations?"
yes I gave him the linq with one line, and for loop. Again : answering his specific question nothing more :) considering this line he wrote a project for myself while I learn C# so I don't want to design the game for him because he'll learn nothing :) but giving him the idea how to compare then he can design it to learn from the his mistakes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.