Home > OS >  Check if an array sorted in ascending order is contained within another array?
Check if an array sorted in ascending order is contained within another array?

Time:10-24

If I have a list,

int[] ints = { 4, 2, 6, 5 };

and I sort the list using Array.Sort(ints), and I've got another array,

int[] i = { 1, 2, 4, 5, 6, 8, 12 };

how do I check that the sorted array, ints is contained within i?

If the array has extra elements,

int[] ints = { 4, 2, 6, 3, 5 };

that are not part of i then this should return false, unlike with this solution:

Here is a Linq solution that should give you what you need:

names.Any(x => subnames.Contains(x))

CodePudding user response:

This gives your desired result:

int firstIndex = Array.IndexOf(i, ints.First());
bool sameSequenceContained = firstIndex != -1
    && i.Skip(firstIndex).Take(ints.Length).SequenceEqual(ints);

So first check if the first integer is contained at all, then use it's index to get the sub-sequence with Skip and Take, then use SequenceEqual to check if it's the same sequence.

Edit: i think it's not that easy since it's possible that there are more than one index of the first item. You could use such an extension method to find all:

public static class Extensions
{
    public static IEnumerable<int> EnumerateAllIndex<T>(this IEnumerable<T> sequence, T item, IEqualityComparer<T> comparer = null)
    {
        if (comparer == null)
        {
            comparer = EqualityComparer<T>.Default;
        }

        int index = 0;
        foreach(T itemInSequence in sequence)
        {
            if(comparer.Equals(item, itemInSequence))
            {
                yield return index;
            }
            index  ;
        }
    }
}

Now you are able to use this readable and efficient query:

bool sameSequenceContained = i.EnumerateAllIndex(ints.First())
    .Any(index => i.Skip(index).Take(ints.Length).SequenceEqual(ints));

CodePudding user response:

I guess, you can use this linq expression.

ints.All(num => i.Contains(num));

Here's the full code.

int[] ints = {4, 2, 6, 5};
Array.Sort(ints);

int[] i = {1, 2, 4, 5, 6, 8, 12};

bool IsPartOf(int[] ints, int[] i)
{
    return ints.All(num => i.Contains(num));
}

Console.WriteLine(IsPartOf(ints, i));
  • Related