Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

155
Vistas
Find index position of partial or entire Array2 in Array1 (sequential order)

Here is what I am trying to do:

String[] Array1 = { "the", "quick", "brown", "fox", "jumps",
                     "over", "the", "lazy", "dog", "in", "the",
                     "barn" };

String[] Array2 = { "in", "the", "barn", "next", "to",
                     "the", "chickens" };


int index = Array.IndexOf(Array1, Array2);
Console.WriteLine("The first occurrence of partial Array2 is at index {0}.", index);

Obviously, the code above returns a value of -1, since the entire Array2 is not found within Array1.

I'd like the result of index to be 9.

What would be the most efficient way to find a partial array within another array?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

We can compare the first element of the second array and find it's index in the first array and then iterate over it comparing successive elements for both to check if the Array2 is completely contained in Array1. Something like this should work:

String[] Array1 = { "the", "quick", "brown", "fox", "jumps",
                 "over", "the", "lazy", "dog", "in", "the",
                 "barn" };

String[] Array2 = { "in", "the", "barn", "next", "to",
                 "the", "chickens" };
                 
int index = Array.IndexOf(Array1, Array2[0]);
int subArrayFlag = 1;

if(Array2.Length + index > Array1.Length)
{
    Console.WriteLine("Array2 cannot be sub array of Array1!");
}
else
{
    for(int i =0;i<Array2.Length; i++)
    {
        if(Array.IndexOf(Array1, Array2[i]) >= 0)
        {
            if(Array2[i] == Array1[index + i])
                continue;
            else
                subArrayFlag = 0;
                break;
        }
        else
        {
            subArrayFlag = 0;
        }
    }
    if(subArrayFlag == 1)
    {
        Console.WriteLine("Array2 is subarray of Array1!");
    }
    else
    {
        Console.WriteLine("Array2 is not sub array of Array1!");
    }
}

Console.WriteLine("The first occurrence of partial Array2 is at index {0}.", index);

The above code can detect if the entire Array2 is contained in Array1 or not!

over 4 years ago · Santiago Trujillo Denunciar

0

You can create a loop and use IndexOf until you got a result:

String[] Array1 = { "the", "quick", "brown", "fox", "jumps","over", "the", "lazy", "dog", "in", "the","barn" };

String[] Array2 = { "in", "the", "barn", "next", "to","the", "chickens" };
                 
int index = -1;
        
for (int j=0; j < Array2.Length; j++){
    index = Array.IndexOf(Array1, Array2[j]);
    if(index >= 0)
       break;
}
over 4 years ago · Santiago Trujillo Denunciar

0

You can use the below method to get the first occurrence index in the Array1. In this way, you don't have to worry about values that exist in Array2 but not Array1.

private int GetFirstOccurenceIndex(string[] arr1, string[] arr2)
    {
        var keyIndexDict = new Dictionary<string, int>();

        for (var i = 0; i < arr1.Length; i++)
        {
            var key = arr1[i];
            if (!keyIndexDict.ContainsKey(key))
                keyIndexDict[key] = i;
        }

        foreach (var key in arr2)
        {
            if (keyIndexDict.TryGetValue(key, out var arr1Index))
                return arr1Index;
        }
        return -1;
    }

Example:

string[] arr1 =
{
        "the", "quick", "brown", "fox", "jumps",
        "over", "the", "lazy", "dog", "in", "the",
        "barn"
};

string[] arr2 =
{
       "someValueDoesntExistInArray1", "in", "the", "barn", "next", "to",
        "the", "chickens"
};


int index = GetFirstOccurenceIndex(arr1, arr2);
Console.WriteLine("The first occurrence of partial Array2 is at index {0}.", index);
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda