Soy nuevo en java. Tengo un problema que, tengo dos matrices parentArray
y subArray
:
parentArray
tiene valores,{1,4,4,3,6}
subArray
tiene valores{4,4,3}
Por lo tanto, la segunda matriz o los llamados subArray
valores están incluidos en la primera-array la llamada parentArray
, con índices a partir de [1,2,3]
. Mi pregunta es ¿cómo podemos devolver el valor del índice del primer elemento del subArray
que también forma parte de parentArray
.
es decir
int[] parentArray = new int[]{1,4,4,3,6};
int[] subArray = new int[]{4,4,3};
Como los valores de subarreglo están en parentArray a partir del índice [1]
, quiero que mi programa para el retorno 1
.
He tratado de comparar dos matrices y la devolución de los elementos comunes de ambas matrices. Pero antes de eso, no se me ocurre ninguna de lógica ya que soy un principiante.
se puede utilizar la Collections.indexOfSubList()
forma siguiente:
List<Integer> parentArray = Arrays.asList(1,4,4,3,6);
List<Integer> subArray = Arrays.asList(4,4,3);
int index = Collections.indexOfSubList(parentArray , subArray);
// index is 1
si se desea implementar para las matrices, echa un vistazo a la fuente de eso y modificarlo un poco:
public static int indexOfSubList(int[] source, int[] target) {
int sourceSize = source.length;
int targetSize = target.length;
int maxCandidate = sourceSize - targetSize;
nextCand:
for (int candidate = 0; candidate <= maxCandidate; candidate++) {
for (int i=0, j=candidate; i<targetSize; i++, j++)
if (!(target[i] == source[j]))
continue nextCand; // Element mismatch, try next cand
return candidate; // All elements of candidate matched target
}
return -1; // No candidate matched the target
}
uso:
int[] parentArray = new int[]{1,1,1,4,4,3,6};
int[] subArray = new int[]{4,4,3};
int index = indexOfSubList(parentArray, subArray);
// index is 3
System.out.println(index);