/ / Comparar una matriz con su espejo: java, matrices, bucles

Comparación de una matriz con su espejo: java, matrices, bucles

Bien, entonces tengo un método que necesita tomar una matriz llena de ints, luego compárelo con su espejo para ver cuál es el espejo más grande con el que coincide. Así, por ejemplo, tengo una matriz [7, 1, 2, 9, 7, 2, 1], la matriz más grande con la que puede coincidir es 2, coincidiendo en [1, 2].

En este momento lo tengo dividido en 3 métodos. Uno que acepta la matriz, otro que invierte la matriz y la devuelve (mirrorArray) y el tercero contando el tamaño de la matriz que coincide (groupCount) Esto es lo que tengo hasta ahora:

public int maxMirror(int[] nums) {
int[] revArray = mirrorArray(nums);

return groupCount(nums, revArray);
}

private int[] mirrorArray(int[] nums) {
int[] newArray = new int[nums.length];

for (int i = nums.length-1, j = 0; i >= 0; i--, j++) {
newArray[j] = nums[i];
}

return newArray;
}

private int groupCount(int[] aFor, int[] bRev) {
int maxCount = 0;
int groupSize = 1;

//get aFor value
for (int i = 0; i < aFor.length; i++) {
int[] tempA = Arrays.copyOfRange(aFor, 0, groupSize);

//loop through bRev and check for matches
for (int j = 0; j < bRev.length; j++) {
int[] tempB = Arrays.copyOfRange(bRev, j, j+groupSize);

if (Arrays.equals(tempA, tempB)) {
maxCount = tempA.length;
}
}

groupSize++;
}
return maxCount;
}

Está fallando en el 3er método en alguna parte (devolviendo un 1 en lugar de un 2) y estoy perplejo por qué los bucles no han devuelto lo que quiero. Cualquier ayuda sería muy apreciada.

Respuestas

5 para la respuesta № 1

Muy bien, tenía curiosidad ...

Aquí está el problema:

int[] tempA = Arrays.copyOfRange(aFor, 0, groupSize);

Siempre está comparando tempB con el primer subArray de longitud groupSize de aFor. Cambia esa línea a

int[] tempA = Arrays.copyOfRange(aFor, i, i + groupSize);

y debería funcionar

EDITAR Mantenga los casos de falla próximos. Parece un problema con la ubicación de incremento de groupSize

   while (groupSize < aFor.length) {
//get aFor value
for (int i = 0; i < aFor.length; i++) {
int[] tempA = Arrays.copyOfRange(aFor, i, i + groupSize);

//loop through bRev and check for matches
for (int j = 0; j < bRev.length; j++) {
int[] tempB = Arrays.copyOfRange(bRev, j, j+groupSize);

if (Arrays.equals(tempA, tempB)) {
maxCount = groupSize;
}
}
}
groupSize++;
}

Este no es el más eficiente, y podría ser un ejercicio divertido de optimizar. Un enfoque inicial sería comenzar groupSize en aFor.length y decremento. Tan pronto como maxCount está asignado, puede regresar temprano.

Editar 2

 int groupSize = aFor.length;
while (groupSize >= 0) {
//get aFor value
for (int i = 0; i <= aFor.length - groupSize; i++) { // note this change
int[] tempA = Arrays.copyOfRange(aFor, i, i + groupSize);

//loop through bRev and check for matches
for (int j = 0; j <= bRev.length - groupSize; j++) { // note this change
int[] tempB = Arrays.copyOfRange(bRev, j, j+groupSize);

if (Arrays.equals(tempA, tempB)) {
return groupSize;
}
}
}
groupSize--;
}
return 1;
}

Lo que sucedía es que las matrices.copyOfRange estaba completando números de límites con ceros. También agregué la opción de salida anticipada que mencioné anteriormente. Probablemente hay más optimizaciones que se pueden hacer


2 para la respuesta № 2

Tu lógica entre tempA y tempB tiene problema:

En cada iteración del primer bucle (original), selecciona 0-> groupSize conjunto de valores y compara exactamente con todas las secuencias de tamaños similares en la matriz inversa, por lo que la primera iteración es

Orignal array (aFor) : [7, 1, 2, 9, 7, 2, 1]
Reverse array (bRev) : [1, 2, 7, 9, 2, 1, 7]
Iteration-1:
tempA=> [7]
tempB=> [1],[2],[7]...
maxCount = 1; (in first iteration, multiple single value matche)

Iteration-2:
tempA=> [7,1]
tempB=> [1,2],[2,7]...
maxCount = 1; (no match of [7,1], maxCount continues from first iteration)

De manera similar, en todas las demás iteraciones no se encontrarían coincidencias de secuencia debido a su conjunto de datos de entrada.

Ahora, si cambia su entrada a [7, 1, 2, 9, 7, 1, 7], maxCount sería 2

Y para la entrada [7, 1, 2, 9, 2, 1, 7], maxCount es 7

Pero eso se debe a la naturaleza de su entrada y problema en su código.

El problema en el código es el bucle externo (aFor loop) no se evalúa para cada secuenciaconjunto, es decir, en la iteración 2, verifica solo el primer conjunto de tamaño 2 ([7,1]) y los conjuntos adicionales ([1,2], [2,9] ..) nunca se comparan, por lo que siempre obtiene maxCount = 1 debido al partido anterior


1 para la respuesta № 3

Sé que esto puede parecer irrelevante para la pregunta, pero intenté hacer las pruebas sin crear nuevas matrices (comparación in situ), espero que esto ayude:

public static int getMaxMirrorSub(int[] arr) {
for (int eqLength = arr.length; eqLength >= 0; eqLength--) {
for (int arrayStart = 0; arrayStart < arr.length; arrayStart++) {
for (int mirrorStart = arr.length - 1; mirrorStart >= eqLength - 1; mirrorStart--) {
int indexArray = arrayStart, indexMirror = mirrorStart;
while(indexArray < arr.length
&& indexMirror >= 0
&& arr[indexArray] == arr[indexMirror]){

indexArray++; indexMirror--;
}

if (indexArray - arrayStart == eqLength)
return eqLength;
}
}
}
return 0;
}

0 para la respuesta № 4
public int maxMirror(int[] nums) {
int[] reverse = null;
int max = 0;
for(int i = 0; i < nums.length; i++) {
for(int k = 0; k < nums.length; k++) {
if(i > k) {
} else {
reverse = reverseSection(nums, i, k);
if(searchFor(reverse, nums)) {
if(reverse.length > max) { max = reverse.length; }
}
}
}
}

return max;
}

public int[] reverseSection(int[] nums, int begin, int end) {
int[] nArray = new int[end - begin + 1];
int numbs = end - begin;
for(int i = begin; i <= end; i++) {
nArray[numbs] = nums[i];
numbs--;
}
return nArray;
}

public boolean searchFor(int[] reverse, int[] nums) {
int index = 0;
boolean check = false;
for(int i = 0; i < nums.length; i++) {
if(nums[i] == reverse[index]) {
index++;

if(index >= reverse.length) {
return true;
}
} else {
index = 0;
}
}
return false;
}