bool hasDuplicate = false;
int[] a = new int[] {1, 2, 3, 4};
int[] b = new int[] { 5, 6, 1, 2, 7, 8 };
I need compare all elements of array A with element of array B and in case of a duplicate element in B, set hasDuplicate on TRUE.
hasDuplicates = a.Intersect(b).Any();
You can use LINQ Intersect method - http://msdn.microsoft.com/en-us/library/system.linq.enumerable.intersect.aspx
Since this is Homework, I will give you a homework answer.
Sure, you could use LINQ and rely on SequenceEqual, Intersect, etc, but that is likely not the point of the exercise.
Given two arrays, you can iterate over the elements in an array using foreach.
int[] someArray;
foreach(int number in someArray)
{
//number is the current item in the loop
}
So, if you have two arrays that are fairly small, you could loop over each number of the first array, then loop over the all the items in the second array and compare. Let's try that. First, we need to correct your array syntax. It should look something like this:
int[] a = new int[] {1, 2, 3, 4};
int[] b = new int[] { 5, 6, 1, 2, 7, 8 };
Note the use of the curly braces {. You were using the syntax to create a N-dimensional array.
bool hasDuplicate = false;
int[] a = new int[] { 1, 2, 3, 4 };
int[] b = new int[] { 5, 6, 7, 8 };
foreach (var numberA in a)
{
foreach (var numberB in b)
{
//Something goes here
}
}
This gets us pretty close. I'd encourage you to try it on your own from here. If you still need help, keep reading.
OK, so we basically need to just check if the numbers are the same. If they are, set hasDuplicate to true.
bool hasDuplicate = false;
int[] a = new int[] { 8, 1, 2, 3, 4 };
int[] b = new int[] { 5, 6, 7, 8 };
foreach (var numberA in a)
{
foreach (var numberB in b)
{
if (numberA == numberB)
{
hasDuplicate = true;
}
}
}
This is a very "brute" force approach. The complexity of the loop is O(n2), but that may not matter in your case. The other answers using LINQ are certainly more efficient, and if efficiency is important, you could consider those. Another option is to "stop" the loops using break if hasDuplicate is true, or place this code in a method and use return to exit the method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With