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

159
Vistas
Encuentre la posición de índice de Array2 parcial o completo en Array1 (orden secuencial)

Esto es lo que estoy tratando de hacer:

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

Obviamente, el código anterior devuelve un valor de -1 , ya que el Array2 completo no se encuentra dentro del Array1.

Me gustaría que el resultado del index sea 9 .

¿Cuál sería la forma más eficiente de encontrar una matriz parcial dentro de otra matriz?

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

0

Podemos comparar el primer elemento de la segunda matriz y encontrar su índice en la primera matriz y luego iterar sobre él comparando elementos sucesivos para que ambos verifiquen si Array2 está completamente contenido en Array1. Algo como esto debería funcionar:

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

¡El código anterior puede detectar si todo el Array2 está contenido en el Array1 o no!

over 4 years ago · Santiago Trujillo Denunciar

0

Puede crear un ciclo y usar IndexOf hasta que obtenga un resultado:

 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

Puede usar el siguiente método para obtener el índice de primera aparición en Array1 . De esta forma, no tiene que preocuparse por los valores que existen en Array2 pero no en 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; }

Ejemplo:

 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