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

Time:02-20

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?

CodePudding user response:

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.)

CodePudding user response:

I've managed to work this out and solve this with :

a.Zip(b, (aPos, bPos) => new { aPosition = aPos, bPosition = bPos }).Distinct().Count()

This will tell me how many distinct sets of both values at the same index and so I can work the rest out from here.

Apologies if my question wasn't clear.

CodePudding user response:

try this sample :

        int [] aa = a.Distinct().ToArray(); 

or :

public static bool HasDuplicates<T>(IList<T> items)
    {
        Dictionary<T, bool> map = new Dictionary<T, bool>();
        for (int i = 0; i < items.Count; i  )
        {
            if (map.ContainsKey(items[i]))
            {
                return true; // has duplicates
            }
            map.Add(items[i], true);
        }
        return false; // no duplicates
    }

and call :

string[] strings = new[] { "1", "2", "3" };
Utility.HasDuplicates(strings)// this will return false

int[] items=new []{1,2,3,1};
Utility.HasDuplicates(items)// this will return true
  • Related