Reputation: 43
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 here is. I need to send in two arrays with numbers in them. I then need to check the arrays through. If ALL the numbers in the array are identical. I need to set my check as true and return it. The only problem is. With the code i set here, where i sent an array with 3,2,3 and one with 1,2,3 it still return check as true.
I'm a newbie at this, so i hoped anyone in here could help me!
Upvotes: 3
Views: 129
Reputation: 14522
My habit is to add the 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]);
}
Upvotes: 0
Reputation: 18127
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 it like this. Your code always return true
, because if one of the element of the arrays are equal the code in your if
statement will return true
. In my case I'm checking for not equal and if this happen just return false
. See that I use other variable which makes this more clear and make it true in the begging.
Upvotes: 1
Reputation: 101701
you are returning 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;
Upvotes: 1
Reputation: 10201
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 items is different, the two arrays are different.
In your code, you effectively said that as soon as one pair of items are equal, the two arrays are equal.
Upvotes: 3