Java - Ayuda Matriz n filas m columas random

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

Ayuda Matriz n filas m columas random

Publicado por Erick (41 intervenciones) el 11/05/2015 10:31:32
No e logrado solucionar este problema agradecería cualquier ayuda


MATRIZ N FILAS M COLUMNA RANDOM NÚMEROS REPETIDOS SI NO HAY MENSAJE:
HACER UNA MATRIZ DE N FILAS POR M COLUMNAS "CARGARLA" CON NÚMEROS ALEATORIOS NO MAYORES A 100 LUEGO ESTABLECER CUANTOS NÚMEROS REPETIDOS HAY "CUALES"

EN CASO DE QUE NO HALLA NINGUNO UN MENSAJE QUE DIGA QUE NO HAY NINGUNO.
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

Ayuda Matriz n filas m columas random

Publicado por Pedro (81 intervenciones) el 11/05/2015 15:03:27
Las mayúsculas.....

Te explicas un poco mal, creo que quieres hacer un programa que se le asigne una matriz de n filas y m columnas e inserte en cada una de las posiciones de la matriz números aleatorios comprendidos entre 0 y 100.

Una vez la matriz cargada de números aleatorios tienes que decir, que números se repiten y con que frecuencia.

¿Correcto?
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: 10
Ha aumentado su posición en 2 puestos en Java (en relación al último mes)
Gráfica de Java

Ayuda Matriz n filas m columas random

Publicado por Erick (41 intervenciones) el 12/05/2015 05:52:26
Correcto.Perdona por no expresarme bien pero creo que me entendiste perfectamente. excepto por la frecuencia es decir que cuantos números se repitieron cuantas veces si hay varios.
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: 10
Ha aumentado su posición en 2 puestos en Java (en relación al último mes)
Gráfica de Java

Ayuda Matriz n filas m columas random

Publicado por Erick (41 intervenciones) el 12/05/2015 09:48:55
esto es lo que he logrado hacer pero no puedo hacer que me diga las veces y el numero que se repiten en la matriz:

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
package matrices1;
 
import java.io.*;
 
public class Matriztarea3 {
 
    public static void main(String[] args) throws IOException {
        BufferedReader tcl = new BufferedReader(new InputStreamReader(System.in));
 
        int M[][];
        int f;
        int c;
        int sumaTotal;
        int sumaFilas[];
        int sumaColumnas[];
        System.out.println("Ingrese el numero de filas: ");
        f = Integer.parseInt(tcl.readLine());
        System.out.println("Ingrese el numero de columnas: ");
        c = Integer.parseInt(tcl.readLine());
        sumaFilas = new int[f];
        sumaColumnas = new int[c];
        M = new int[f][c];
        llenar(M, f, c);
        sumaTotal = 0;
        for (int i = 0; i < f; i++) {
            for (int k = 0; k < c; k++) {
                sumaTotal = sumaTotal + M[i][k];
            }
        }
        for (int k = 0; k < c; k++) {
            for (int i = 0; i < f; i++) {
            }
        }
        for (int i = 0; i < f; i++) {
            for (int k = 0; k < c; k++) {
                System.out.print(" " + M[i][k]);
            }
            System.out.println(" ");
        }
        for (int k = 0; k < c; k++) {
            System.out.print(" ");
        }
    }
 
    public static void llenar(int M[][], int n, int m) {
        for (int i = 0; i < n; i++) {
            for (int k = 0; k < m; k++) {
                M[i][k] = (int) (Math.random() * 100);
            }
        }
    }
}
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

Ayuda Matriz n filas m columas random

Publicado por Pedro (81 intervenciones) el 12/05/2015 16:25:22
Tu problema es que quieres hacerlo todo en el mismo método y no divides el código en funcionalidades. Así es muy difícil hacerlo.

Entiendo que crear métodos estáticos sabes porque lo has puesto en el código y manejar excepciones algo debes saber.

Así es como yo lo hubiera hecho si no me dejasen crear clases para el ejercicio, tomate tu tiempo e intenta comprender cada método por separado.

Espero que te sirva de ayuda para este ejercicio y para el futuro, la regla de oro es divide y vencerás. Como observaras cada método tiene poco código y hace que la comprensión del método sea rápida y fácil.

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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
package matrizericklwp;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
/**
 *
 * @author Pedro Antonio Cordero Morales
 */
public class MatrizErickLWP {
 
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        int[][] matriz = null;
 
        //Pedimos al usuario los datos por consola para que defina las filas y columnas
        try {
            matriz = generarMatrizCargada();
        } catch (IOException ex) {
            System.out.println("Error en la lectura de la fila y/o columna");
            System.exit(0);
        }
 
        //Pintamos la matriz por consola
        dibujarMatriz(matriz);
 
        //Generar resultado
        getResultados(matriz);
 
    }
 
    public static int[][] generarMatrizCargada() throws IOException {
 
        Integer filas, columnas;
        int[][] matriz;
        BufferedReader tcl = new BufferedReader(new InputStreamReader(System.in));
 
        System.out.println("Ingrese el numero de filas: ");
        filas = Integer.parseInt(tcl.readLine());
        System.out.println("Ingrese el numero de columnas: ");
        columnas = Integer.parseInt(tcl.readLine());
 
        matriz = new int[filas][columnas];
 
        cargar(matriz);
 
        return matriz;
 
    }
 
    public static void cargar(int[][] matriz) {
 
        for (int i = 0; i < matriz.length; i++) {
 
            for (int k = 0; k < matriz[i].length; k++) {
                matriz[i][k] = (int) (Math.random() * 100);
            }
 
        }
 
    }
 
    public static void dibujarMatriz(int[][] matriz) {
 
        System.out.println("\n\n Matriz resultante:\n");
 
        for (int[] fila : matriz) {
 
            for (int i = 0; i < fila.length; i++) {
                System.out.print(fila[i] + "\t");
            }
 
            System.out.print("\n");
        }
 
    }
 
    public static void getResultados(int[][] matriz) {
 
        if (existeAlMenosUnNumeroRepetido(matriz)) {
 
            int[] listaRepetidos = controlDeNumerosRepetidos(matriz);
            int[][] matrizResultado = obtenerMatrizConNumeroRepetidoyVeces(listaRepetidos);
 
            dibujarResultados(matrizResultado);
 
        } else {
            System.out.println("No hay ningún numero repetido en la matriz generada");
        }
 
    }
 
    public static boolean existeAlMenosUnNumeroRepetido(int[][] matriz) {
 
        boolean existeRepetido = false;
        int[] lista = controlDeNumerosRepetidos(matriz);
 
        for (int i : lista) {
            existeRepetido = existeRepetido || i > 1;
        }
 
        return existeRepetido;
    }
 
    public static int[] controlDeNumerosRepetidos(int[][] matriz) {
 
        int[] contadorRepetidos = new int[100];
 
        for (int[] fila : matriz) {
 
            for (int i = 0; i < fila.length; i++) {
                contadorRepetidos[ fila[i] ]++;
            }
 
        }
 
        return contadorRepetidos;
    }
 
    public static int[][] obtenerMatrizConNumeroRepetidoyVeces(int[] listaNumeros) {
 
        int filas = cuantosNumerosRepetidosExisten(listaNumeros);
        int posicion = 0;
 
        int[][] sinCeros = new int[filas][2];
 
        for (int ordinarLista = 0; ordinarLista < listaNumeros.length; ordinarLista++) {
 
            if (listaNumeros[ordinarLista] > 1) {
                sinCeros[posicion][0] = ordinarLista;
                sinCeros[posicion][1] = listaNumeros[ordinarLista];
                posicion++;
            }
        }
 
        return sinCeros;
    }
 
    public static int cuantosNumerosRepetidosExisten(int[] listaNumeros) {
 
        int numerosRepetidos = 0;
 
        for (int i = 0; i < listaNumeros.length; i++) {
 
            if (listaNumeros[i] > 1) {
                numerosRepetidos++;
            }
        }
 
        return numerosRepetidos;
    }
 
    public static void dibujarResultados(int[][] resultado) {
 
        System.out.println("\n\n Números que se han repetido:\n");
 
        for (int[] fila : resultado) {
            System.out.print("Número: " + fila[0] + "\t" + "Veces repetido: " + fila[1]);
            System.out.print("\n");
        }
 
    }
 
}
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
Imágen de perfil de jonathan

Ayuda Matriz n filas m columas random

Publicado por jonathan (4 intervenciones) el 17/05/2015 05:35:26
excelente codigo y tan bien documentado señor antonio en el caso mio debo realizar un algoritmo que internamente genere la matriz [5][5] y sea de tipo random con numeros de 0 a 100 la idea es poder multiplicar esta matriz aleatoria por ella misma por 4 veces asi que luego pueda calcular la cadena de markov con dicha matriz resultante


hasta ahora ya cree la matriz aleatoria 5 x 5 y pude sumar sus filas

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
package m1;
 
import java.util.Random;
import java.util.*;
 
  public class Matriz {
 
 
    private int matriz [][];
    private int matriz2 [][];
    private int matriz3 [][];
    private Random random;
    private int totalf=0;
    private int totalc=0;
    private double promedio = 0;
    private double p;
 
    public Matriz(){
        matriz = new int[5][5];
        random = new Random();
        //matriz2 = new int[5][5];
    }
 
    public void llenarMatriz(){
        try{
            for(int i  = 0;i<matriz.length;i++){
                for (int  j = 0;j<matriz.length;j++){
                    matriz[i][j] = random.nextInt(100);
 
                }
            }
        }catch(Exception e){
           System.out.println(e.getMessage());
        }
}
 
    public void multimatriz(){
 
    { // abre primer ciclo for
    for ( int j=0;j<matriz.length; j++)
                         { // abre el segundo ciclo for
    for ( int i=0;i< matriz.length ; i++ )
            matriz2 = matriz[i][j]*matriz[i][j];
     }
       }
     }
 
 
     public void imprimirMatriz() {
        for(int f=0;f<matriz.length;f++) {
            double promedio = 0;
            for(int c=0;c<matriz[f].length;c++) {
 
                System.out.print(matriz[f][c]+" ");
                totalf = totalf + matriz[f][c];
                promedio = promedio + matriz[f][c];
 
            }
 
              System.out.println("   su total es: "+totalf +"     su promedio es:   "+(promedio/matriz[f].length));
 
 
            totalf = 0;
            totalc = 0;
        }
            }
  }
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