Aenu
Aenu

Reputation: 33

How to compare two 2d arrays

i am using visual studio c# win form. . . i have 2d array of textboxes and i have another 2d array of valid solved sudoku i want to compare textbox's text to sudoku array but its not working.Here is my code:

        private void Isvalid()
        {
            for (int i = 0; i < 4; i++)
                for (int j = 0; j < 4; j++)
                    if (copy[i, j] == textbox[i, j].Text)
                        isvalid = true;


        }
        private void check()
        {
            Isvalid();
            if (isvalid)
                MessageBox.Show("NO");
            else
                MessageBox.Show("YES");

        }

Can anyone plz help me. . . THANx in Advance. . . Thanx to all who answerd. . .

Upvotes: 3

Views: 4718

Answers (4)

GvS
GvS

Reputation: 52501

You do not (re)set the isvalid variable to false, if the arrays are not equal.

You pass the result of the Isvalid method through a shared variable. Your code will be much clearer if you pass the result of the comparison as the method result.

private bool Isvalid()
{
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {
            if (copy[i, j] != textbox[i, j].Text) {
                return false;  // If one is not equal, the two arrays differ
            }
        }
    }
    return true;
}

Now you can test for:

if (Isvalid()) {
   // your code here
}

Even better will be if you pass the two arrays as arguments.

Upvotes: 1

koool
koool

Reputation: 15527

textbox[i, j].Text

here you need to convert the values in the textbox matrix to integer before comparing. That will solve the problem.

Also you need to set invalid as false and after making it true break out of loop

Upvotes: 1

takrl
takrl

Reputation: 6482

Try this:

private void Isvalid()
{
    isvalid = true;
    for (int i = 0; i < 4; i++)
        for (int j = 0; j < 4; j++)
            if (copy[i, j] != textbox[i, j].Text)
            {
                isvalid = false;
                return;
            }
}

In your routine, you'd set isvalid to true whenever one number matches. You'd rather need to set it to false if a number doesn't match.

Upvotes: 0

Russ Clarke
Russ Clarke

Reputation: 17909

I would put a breakpoint on the

if (copy[i, j] == textbox[i, j].Text)

line and visually see if what you see in the Text box is what the array contains. It might be as simple as needing to do a case-insensitive comparison.

Upvotes: 1

Related Questions