Compare two int arrays

I wrote this code:

class Program
{
    static void Main(string[] args)
    {
        Test t = new Test();
        int[] tal1 = { 3, 2, 3};
        int[] tal2 = { 1, 2, 3};

        Console.WriteLine(t.theSameInBoth(tal1,tal2));
    }
}

class Test
{
    public Boolean theSameInBoth(int[] a, int[] b)
    {
        bool check = false;

        if (a.Length == b.Length)
        {
            for (int i = 0; i < a.Length; i++)
                if (a[i].Equals(b[i]))
                {
                    check = true;
                    return check;
                }
        }

        return check;
    }
}

      

So, the deal is here. I need to send two arrays with numbers to them. Then I need to check the arrays. If ALL numbers in the array are identical. I need to set my check as valid and return it. The only problem. With the code i listed here, where I sent an array with 3,2,3 and one with 1,2,3, it still returns the check as true.

I'm new to this, so I was hoping someone here could help me!

+3


source to share


4 answers


You need to reverse the tests:

class Test
{
    public bool theSameInBoth(int[] a, int[] b)
    {
        if (a.Length == b.Length)
        {
            for (int i = 0; i < a.Length; i++)
            {
                if (a[i] != b[i])
                {
                    return false;
                }
            }

            return true;
        }

        return false;
    }
}

      



As soon as one pair of elements is different, the two arrays are different.

In your code, you effectively said that once one pair of elements is equal, the two arrays are equal.

+3


source


you return as soon as you find the first match. You need something like this:



bool check = true;

if (a.Length == b.Length)
{
   for (int i = 0; i < a.Length; i++)
   {
      if (!a[i].Equals(b[i]))
      {
            check = false;
            break;
       }

   }
   return check;
}
else 
  return false;

      

+1


source


bool isIndentical = true;

if (a.Length == b.Length)
{
    for (int i = 0; i < a.Length; i++)
         if (!a[i].Equals(b[i]))
         {
            isIndentical = false;
            return check;
         }
}

return isIndetical;

      

Try this. Your code always returns true

, because if one of the array elements is equal, the code in your statement if

will return true

. In my case, I check that you are not equal and if it does, return false

. See that I am using a different variable that makes this clearer and makes it true in begging.

+1


source


My habit is to add a Linq solution:

public bool IsSame(int[] a, int[] b)
{
    return a.Length == b.Length &&
           a.Select((num, index) => num == b[index]).All(b => b);
}

      

Another cool Linq approach:

public bool IsSame(int[] a, int[] b)
{
    return a.Length == b.Length &&
           Enumerable.Range(0, a.Length).All(i => a[i] == b[i]);
}

      

0


source







All Articles