Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Map;
- import java.util.TreeMap;
- public class Ejercicio03 {
- public Map<Integer, Integer> contarAparicionesDeLosValores(int fila[]){
- int elementosDeLaFila = fila.length;
- //Uso un mapa que como clave tiene el numero y como valor tiene la
- //cantidad de veces que este numero se repite en la fila
- Map<Integer, Integer> numeros = new TreeMap<Integer, Integer>();
- for(int i=0; i<elementosDeLaFila; i++) {
- if(numeros.containsKey(fila[i])) {
- //Si el numero ya esta mapeado le sumo 1
- int contNumero = numeros.get(fila[i]);
- contNumero++;
- numeros.replace(fila[i], contNumero);
- }
- else {
- //Si el numero no esta mapeado inicializo su contador en 1
- numeros.put(fila[i], 1);
- }
- }
- return numeros;
- }
- public int calcularModa(Map<Integer, Integer> numeros) {
- //Recorro el map para ver de los numeros que mas veces
- //se repiten cual es el mayor
- int mayorVeces = 0, moda = 0;
- for (Map.Entry<Integer, Integer> numero : numeros.entrySet()) {
- if(numero.getValue()>mayorVeces) {
- mayorVeces = numero.getValue();
- moda = numero.getKey();
- }
- else if(numero.getValue()==mayorVeces){
- if(numero.getKey()>moda) {
- moda = numero.getKey();
- }
- }
- }
- return moda;
- }
- public int[] modasDeCadaFila(int matriz[][]) {
- int cantFilas = matriz.length;
- int vectorModas[] = new int[cantFilas];
- for(int i=0; i<cantFilas; i++) {
- Map<Integer, Integer> numeros = contarAparicionesDeLosValores(matriz[i]);
- vectorModas[i] = calcularModa(numeros);
- }
- return vectorModas;
- }
- public void imprimirVector(int[] vector) {
- for (int i = 0; i < vector.length; i++) {
- System.out.print(vector[i] + " ");
- }
- }
- public static void main(String[] args) {
- int[][] matriz = {
- {1,2,3,4},
- {5,-6,-6,20},
- {1,1,10,10}};
- int vectorModas[] = new int[matriz.length];
- Ejercicio03 eje = new Ejercicio03();
- vectorModas = eje.modasDeCadaFila(matriz);
- eje.imprimirVector(vectorModas);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement