Java - Ayuda con Recursividad

 
Vista:
sin imagen de perfil
Val: 5
Ha aumentado su posición en 6 puestos en Java (en relación al último mes)
Gráfica de Java

Ayuda con Recursividad

Publicado por Aitor (2 intervenciones) el 03/11/2020 22:49:55
Me dan el siguiente código y me piden que compare las matrices de las casos dados dividiendolos en vectores con Arrays.CopyOfRange y pasando los fragmentos por SonVectoresIguales, que es el método que compará los fragmentos. Todo ello usando recursividad. Si alguien sabe como puedo aplicar recursividad me haría un gran favor.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
public class Solucion {
 
    public static int n = 3; //la n la tomaremos como el tamaño de los vectores de la matriz
 
    public static void main(String[] args) {
        Solucion solucion = new Solucion();
 
        solucion.problema();
    }
 
    public void problema() {
        System.out.println("Inicio problema");
 
        int[][] matriz1 = {{1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12}};
 
        int[][] matriz2 = {{9, 10, 11, 12},
        {5, 6, 7, 8},
        {1, 2, 3, 4}};
 
        int[][] matriz3 = {{1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}};
 
        System.out.println("Test 1:");
        System.out.println(String.format("Matriz1 == Matriz1: %b", sonMatricesIguales(matriz1, matriz1, matriz1.length)));
 
        System.out.println("\n\nTest 2:");
        System.out.println(String.format("Matriz1 == Matriz2: %b", sonMatricesIguales(matriz1, matriz2, matriz1.length)));
 
        System.out.println("\n\nTest 3:");
        System.out.println(String.format("Matriz2 == Matriz3: %b", sonMatricesIguales(matriz2, matriz3, matriz2.length)));
 
        System.out.println("Fin problema\n");
    }
 
    public boolean sonMatricesIguales(int[][] matriz1, int[][] matriz2, int fila) {
        boolean sonIguales = true;
 
        } else {
            return sonMatricesIguales(matriz1, matriz2, fila);
        }
        return sonIguales;
    }
 
    public boolean sonVectoresIguales(int[] vector1, int[] vector2) {
        boolean sonIguales = true;
        if (vector1[n] != vector2[n]) {
            return false;
        } else if (n == 0) {
            return true;
        } else {
            n--;
            // System.out.println(n);
            return sonVectoresIguales(vector1, vector2);
        }
 
    }
 
    //return sonIguales ;
    public static void MatrizAVector(int m1[][], int n) {
 
        int v1[] = {};
        int i, j;
        int contador = 0;
        for (i = 0; i < n; i++) {
            for (j = 0; j < n; j++) {
                v1[contador] = m1[i][j];
                contador = contador + 1;
                System.out.println(v1);
            }
        }
    }
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
sin imagen de perfil
Val: 186
Ha disminuido su posición en 2 puestos en Java (en relación al último mes)
Gráfica de Java

Ayuda con Recursividad

Publicado por Juan (70 intervenciones) el 04/11/2020 10:18:32
1
 

el formato que uso aqui:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
return (sonVectoresIguales(matriz1[fila],matriz2[fila],matriz1[fila].length-1)) ? sonMatricesIguales(matriz1, matriz2, (fila-1)) : false;public void problema() {
    System.out.println("Inicio problema");
 
    int[][] matriz1 = {{1, 2, 3, 4},
    {5, 6, 7, 8},
    {9, 10, 11, 12}};
 
    int[][] matriz2 = {{9, 10, 11, 12},
    {5, 6, 7, 8},
    {1, 2, 3, 4}};
 
    int[][] matriz3 = {{1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}};
 
    System.out.println("Test 1:");
    System.out.println(String.format("Matriz1 == Matriz1: %b", sonMatricesIguales(matriz1, matriz1, matriz1.length-1)));
 
    System.out.println("\n\nTest 2:");
    System.out.println(String.format("Matriz1 == Matriz2: %b", sonMatricesIguales(matriz1, matriz2, matriz1.length-1)));
 
    System.out.println("\n\nTest 3:");
    System.out.println(String.format("Matriz2 == Matriz3: %b", sonMatricesIguales(matriz2, matriz3, matriz2.length-1)));
 
    System.out.println("Fin problema\n");
}
 
public boolean sonMatricesIguales(int[][] matriz1, int[][] matriz2, int fila) {
    if (matriz1.length!=matriz2.length) return false;
    if(fila>=0) {
        return (sonVectoresIguales(matriz1[fila],matriz2[fila],matriz1[fila].length-1)) ? sonMatricesIguales(matriz1, matriz2, (fila-1)) : false;
    }
    return true;
}
 
public boolean sonVectoresIguales(int[] vector1, int[] vector2,int columna) {
    if (vector1.length!=vector2.length) return false;
    if (columna>0) {
        return (vector1[columna]==vector2[columna]) ? sonVectoresIguales(vector1, vector2, (columna-1)) : false;
    }
    return true;
}

es: (condicion) ? (accion si se cumple) : (accion si no se cumple)

entonces: si las vectores en esa matriz son iguales vuelve a llamar a la funcion, si no son iguales devuelves false;

es lo mismo que poner:

1
2
3
4
if (sonVectoresIguales(matriz1[fila],matriz2[fila],matriz1[fila].length-1))
    return sonMatricesIguales(matriz1, matriz2, (fila-1));
else
    return false;

Cualquier duda me dices y te lo explico ;)
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 5
Ha aumentado su posición en 6 puestos en Java (en relación al último mes)
Gráfica de Java

Ayuda con Recursividad

Publicado por Aitor (2 intervenciones) el 04/11/2020 12:02:38
Muchas gracias por contestar, lo he ido a probar y me han saltado una serie de excepciones. Tengo también una pregunta sobre el método vectores iguales, es que me piden hacerlo sin modificar los parámetros de entrada, es decir , con
1
2
public boolean sonVectoresIguales(int[] vector1, int[] vector2){
}

y compararlo troceando la matriz con Arrays.CopyOfRange por filas .

Captura

Disculpa si no me explico del todo bien, pero es mi primera vez en este tipo de foros y no estoy acostumbrado :/
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 186
Ha disminuido su posición en 2 puestos en Java (en relación al último mes)
Gráfica de Java

Ayuda con Recursividad

Publicado por Juan (70 intervenciones) el 06/11/2020 10:38:59
vale ya eso es otra cosa jeje. No se que tipo de excepción te arroja, si te vuelve a arrojar una especifica que excepción es para ayudarte, seguramente te arrojo la excepción java.lang.ArrayIndexOutOfBoundsException porque envías por parámetro matriz1.length si tu matriz es de 3 filas, te enviara un 3 al procedimiento, pero los índices o posiciones de los arrays empiezan en cero, por lo que las posiciones que tienes son 0, 1 y 2 no existe la posición 3. tendrías que pasar (matriz1.length -1).

Luego la única manera que se me ocurre ahora, es comparar la primera posición de los vectores, y si son iguales llamamos nuevamente al método, pero enviando el vector con la posición inicial quitada, usando el método que te dicen, posiblemente exista otra manera, pero ahora se me ocurre esa. quedando así:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public void problema() {
	        System.out.println("Inicio problema");
 
	        int[][] matriz1 = {{1, 2, 3, 4},
	        {5, 6, 7, 8},
	        {9, 10, 11, 12}};
 
	        int[][] matriz2 = {{9, 10, 11, 12},
	        {5, 6, 7, 8},
	        {1, 2, 3, 4}};
 
	        int[][] matriz3 = {{1, 2, 3},
	        {4, 5, 6},
	        {7, 8, 9}};
 
	        System.out.println("Test 1:");
	        System.out.println(String.format("Matriz1 == Matriz1: %b", sonMatricesIguales(matriz1, matriz1, matriz1.length-1)));
 
	        System.out.println("\n\nTest 2:");
	        System.out.println(String.format("Matriz1 == Matriz2: %b", sonMatricesIguales(matriz1, matriz2, matriz1.length-1)));
 
	        System.out.println("\n\nTest 3:");
	        System.out.println(String.format("Matriz2 == Matriz3: %b", sonMatricesIguales(matriz2, matriz3, matriz2.length-1)));
 
	        System.out.println("Fin problema\n");
	    }
 
	    public boolean sonMatricesIguales(int[][] matriz1, int[][] matriz2, int fila) {
	        if (matriz1.length!=matriz2.length) return false;
	        if(fila>=0) {
	            return (sonVectoresIguales(matriz1[fila],matriz2[fila])) ? sonMatricesIguales(matriz1, matriz2, (fila-1)) : false;
	        }
	        return true;
	    }
 
	    public boolean sonVectoresIguales(int[] vector1, int[] vector2) {
	    	if (vector1.length!=vector2.length) return false;
	    	 if (vector1.length>0)
		    	 return (vector1[0]!=vector2[0]) ? false : sonVectoresIguales(Arrays.copyOfRange(vector1, 1, vector1.length),Arrays.copyOfRange(vector2, 1, vector2.length));
		    return true;
	    }
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar