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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.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:
Note the use of the curly braces
{. You were using the syntax to create a N-dimensional array.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
hasDuplicateto 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
breakifhasDuplicateis true, or place this code in a method and usereturnto exit the method.