2
int[] a = new int[] { 1, 2, 3, 4 };
int[] b = new int[] { 5, 6, 1, 2, 7, 8 };
int Count = 0;
for (int i = 0; i < a.Length; i++)
{
     for (int j = 0; j < b.Length; j++)
     {
         if (a[i] == b[j])
         { 
             Count++; 
             break; 
         }
     }        
 } 

Console.WriteLine(Count);
Console.ReadLine();    

Above is a simple program which can search through both arrays and find duplicates between them. However I am having difficulty when making the first array a 2D array as I get an error running the code below 'Index was outside the bounds of the array.' I really can't figure out what to do so I would be grateful for any help.

int[][] a = {new int[] { 1, 2, 3, 4 }, new int[] { 3, 9, 9 }};      
int[] b = new int[] { 5, 6, 1, 2, 7, 8 };
int Count = 0;
for (int i = 0; i < a.Length; i++)
{
     for (int j = 0; j < b.Length; j++)
     {
         if (b[j] == a[i][j])
         { 
             Count++; 
             break; 
         }
     }
} 

Console.WriteLine(Count);
Console.ReadLine();
5
  • 1
    Enumerable.Intersect<TSource> Commented Mar 27, 2015 at 3:28
  • 2
    a[i]th array length is a[i].Length, not b.Length. PS: I like your nickname Commented Mar 27, 2015 at 3:29
  • Your b has 6 elements, and j will be as big as 5. However, your second dimension only has 3 elements and any index over 2, which your code will try to do inside the nested for loop, will cause an indexoutofbounds. Commented Mar 27, 2015 at 3:31
  • Jagged arrays... Ugh. You'd have to iterate over every sub array to get its length first. Or... Use zerkms's comment. Your current code looks at how many sub arrays you have, not how long any of them are. Commented Mar 27, 2015 at 3:33
  • An information that might be useful: you can also use Array.GetLength() to get the length of a specified dimension, the method wants an integer that specifies the dimension you want the length of so GetLength(0) gives you the count of elements in the first dimension, GetLength(1) the count of elements in the second dimension and so on. Commented Mar 27, 2015 at 8:33

6 Answers 6

1

I assume you want to find duplicates between the 2d array and a 1d array.

      int[][] a = { new int[] { 1, 2, 3, 4 }, new int[] { 3, 9, 9 } };
        int[] b = new int[] { 5, 6, 1, 2, 7, 8 };
        int Count = 0;
        for (int h = 0; h < a.Length; h++)
        {
            for (int i = 0; i < a[h].Length; i++)
            {
                for (int j = 0; j < b.Length; j++)
                {
                    if (b[j] == a[h][i])
                    {
                        Count++;
                        break;
                    }
                }
            }
        }

Or in Linq ;)

int Count = (from i in a from j in i from k in b where k == j select j).Count();

= Found 2 duplicates between a2 and b?

Edit for new spec

2nd edit for storing duplicates for each 2d array element.

   var duplicates = new List<int>();
        foreach (var i in a)
        {
            var duplicate = 0;
            foreach (var j in i)
            {
                foreach (var k in b)
                {
                    if (k == j)
                    {
                        duplicate++;
                    }
                }
            }
            duplicates.Add(duplicate);
        }

Or linq again ;)

var duplicates = a.Select(i => (from j in i from k in b where k == j select j).Count()).ToList();

Update 3: For your selected code format:

var duplicates = new List<int>();
        for (int h = 0; h < a.Length; h++)
        {
            var duplicate = 0;
            for (int i = 0; i < a[h].Length; i++)
            {
                for (int j = 0; j < b.Length; j++)
                {
                    if (b[j] == a[h][i])
                    {
                        duplicate++;
                        break;
                    }
                }
            }
            duplicates.Add(duplicate);
        }

Added duplicate output:

     for (int d = 0; d < duplicates.Count; d++)
        {
            Console.WriteLine(duplicates[d]);
        }
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for the help, yes I am trying to find duplicates between the 2d array and the 1d array so for example the program would write 2 duplicated in the first array and 0 duplicates in the second.
Yes that should work then, also if you want to use linq the 2nd one liner does the exact same thing.
How can you distinguish the duplicates per array rather than just display the total count?
Check the update, each duplicate group should now be added to the duplicate list.
if you need me to write it for you in the for(int i=0;i<x;i++){} format just let me know and ill repost.
|
1
//initialize stuff here
for(int i = 0; i<a.length; ++i) {//iterate over the rows in a
    for(int j = 0; j<a[i].length; ++j) {//iterate over columns in a
        for(int k = 0; k < b.length; ++k) {//iterate over b
            if(a[i][j] == b[k]) { 
                //increment stuff here
            }//end if
        }//end for k
    }//end for j
//print stuff for each sub array here 
}end for i 
//print stuff here for all sub arrays 

Comments

1

You can try with a foreach

            foreach (var val1 in a)
            {
                foreach (var val2 in val1)
                {
                    foreach (var val3 in b)
                    {
                        if (val3 == val2)
                        {
                            Count++;
                        }
                    }
                }
            }

Or with a another for

        for (int i = 0; i < a.Length; i++)
        {
            var innerArray = a[i];
            for (int f = 0; f < innerArray.Length; f++)
            {
                for (int j = 0; j < b.Length; j++)
                {
                    if (b[j] == innerArray[f])
                    {
                        Count++;
                    }
                }
            } 
        } 

Comments

1

You can use Linq expression as well, I guess it's much easier than loop

a.SelectMany(x => x).Count(x => b.Contains(x))

Comments

0

Your array a is actually an array with 2 elements, one that is 4 elements long, and the other that is 3 elements long. Your inner loop is iterating over each of those arrays for every element of b, so that when it hits the 5th element of b, b[4] compared against a[0][4], it's out of bounds, since the last element of a[0] is a[0][3], but you are trying to compare to a[0][4]. Also, do you really want to break after you've found a match?

If you want to find all duplicates, the simplest bets are probably either @peyman, or you might use the idea of commenter @zerkms, Enumerable.Intersect<TSource>, assuming flattening a into 1d first.

int[] flattened = a.SelectMany(item => item).ToArray();
Count = b.Intersect(flattened).Count();

which is the same as:

b.Intersect(a.SelectMany(item => item).ToArray()).Count();

5 Comments

Faster, but initially wrong. ;-]. I had to revise.
I didn't do downvote, but I guess cause your code has problem with k, b array can have less or more member than a[i]
Good point, @Peyman. But that's the problem with the whole approach. I'll edit to make that danger clear.
I don't know why no one use Linq Expression, it should much easier
Fixed flaws in my solution.
0

There's a much simpler way still. Convert the 2D (or more) array to 1D then use a regular SequenceEqual to compare them.

static bool AreEqual<T>(T[,] array1, T[,] array2)
{
   return array1.Cast<T>().SequenceEqual(array2.Cast<T>());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.