Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if 2 int arrays contain only unique numbers at the same index

If I have 2 int arrays a and b and they contain data like this..

a[0] = 1
a[1] = 3
a[2] = 7

b[0] = 6
b[1] = 3
b[2] = 5

How can I check if all the pairs of numbers are unique e.g. that each combination of a[i] and b[i] at the same index is not repeated in the rest of the array… So the above data would pass but if I introduced this below it would fail..

a[24] = 7
b[24] = 5

Because this combination already exists in the array at index 2. Can I do this in LINQ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If the order of the values in the pairs over the two arrays is significant (i.e. a[0] == 1, b[0] == 2 is considered different from a[0] == 2, b[0] == 1) then one way to check for uniqueness using Linq is as follows:

bool unique = a.Zip(b).Distinct().Count() == a.Length;

If the order of the values in the pairs is NOT significant, it’s slightly more fiddly:

bool unique = a.Zip(b).DistinctBy(
     x => (Math.Min(x.First, x.Second), Math.Max(x.First,x.Second)))
.Count() == a.Length;

These solutions assume that missing values in one of the arrays will be ignored.

(Note: DistinctBy() is only available in .Net 6.0 or later, or via a NuGet package.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading