C: A simple way to determine whether a set is a subset of another set

  • 2021-09-16 07:44:47
  • OfStack

Seeing this title, our first thought is to loop through one of the arrays to determine whether each element in the array appears in the other array, so as to determine whether the array is a subset of the other array, but this is too complicated. Is there a simple way?

For example, there are two sets:

string[] bigArr = new string[] { "a", "b", "c" };
string[] smallArr = new string[] { "a", "b"};

It is now necessary to determine whether smallArr is a subset of bigArr. Just compare bigArr with smallArr and find the difference set. If the number of difference sets is greater than 0, it means that smallArr is a subset of bigArr.

// On the basis of large set, the difference set of large set is obtained according to small set 
var exceptArr = bigArr.Except(smallArr);
// Determine whether it is a subset
if(exceptArr.Any())
{
    Console.WriteLine("samllArr Yes bigArr Adj. 1 Subset ");
}
else
{
    Console.WriteLine("samllArr No bigArr Adj. 1 Subset ");
}

In the above way, we can only judge whether it is a subset, that is, the set element of the subset is always smaller than the larger set.

Sometimes, there is a need to judge whether bigArr contains smallArr, that is, smallArr can be a subset of bigArr, or it can be identical to bigArr.

// Determine whether it is a subset or 2 Set of 1 Sample 
if(smallArr.All(t => bigArr.Any(b => b==t)))
{
    Console.WriteLine("samllArr Yes bigArr Adj. 1 Subset or 1 Sample ");
}
else
{
    Console.WriteLine("samllArr No bigArr Adj. 1 Subset or 1 Sample ");
}


Related articles: