jueves, 3 de noviembre de 2011

Algoritmos básicos en Java

Multiplicación de 2 Matrices 
Se tiene dos matrices A y B, se desea obtener el producto de la multiplicacion de A y B.
Ejemplo

A | 2  3 |    B | 4  2  1 |    AxB = | 11  13  8 |
    | 1  2 |       | 1  3  2 |                | 6    8   5 |




Código Java, considerando el ingreso de datos, procesamiento y salida.

package multiplicacion_matrices;
import java.io.*;


public class Multiplicacion_Matrices {
    public static void main(String[] args) throws IOException {
        BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
     
        // Definicion de variables
        int [][] matrizA;
        int [][] matrizB;
        int [][] matrizC;
        int [][] mult;
        int sum=0, mul, NfilA, NmatrizAB, NcolB, i=0, j=0, k=0, valor;
     
        //Lectura de datos
        System.out.println("---------- Matriz A ---------");
        System.out.println("Cantidad de filas A: ");
        NfilA = Integer.parseInt(br.readLine());
        System.out.println("Cantidad de columnas A: ");
        NmatrizAB = Integer.parseInt(br.readLine());       
        System.out.println("---------- Matriz B ---------");
        System.out.println("Cantidad de filas B: "+NmatrizAB);
        System.out.println("Cantidad de columnas B: ");
        NcolB = Integer.parseInt(br.readLine());           
        //Iniciando el arreglo
        matrizA = new int[NfilA][NmatrizAB];
        matrizB = new int[NmatrizAB][NcolB];
        matrizC = new int[NfilA][NcolB];
        mult =    new int[NfilA][NcolB];     
        //Insertando valores
        System.out.println("\n----- Valores de Matriz A -----");
        for(i=0; i<NfilA;i++)
        {   k++;
          for(j=0;j<NmatrizAB;j++){
            System.out.println("Ingrese Fila"+(k)+" y Col"+(j+1)+": ");          
            valor = Integer.parseInt(br.readLine());
            matrizA[i][j] = valor;
        }}
        k=0;     
        System.out.println("\n----- Valores de Matriz B -----");
        for(i=0; i<NmatrizAB;i++)
        {   k++;
          for(j=0;j<NcolB;j++)  {
            System.out.println("Ingrese Fila"+(k)+" y Col"+(j+1));          
            valor = Integer.parseInt(br.readLine());
            matrizB[i][j] = valor;
        }}    
     
        //Procesamiento
        for(i=0; i<NfilA;i++)
        {    for(j=0;j<NcolB;j++)
            {
               sum=0;
               for(k=0;k<NmatrizAB;k++)
               {
                 int m = matrizA[i][k] * matrizB[k][j];
                 sum = sum+m;
                }
            matrizC[i][j]= sum;
            }    }
        
      //Salida de Datos
     System.out.println("Respuesta Matriz C de " +NcolB+"x"+NfilA);
     for(i=0;i<NmatrizAB;i++)
     {   for(j=0;j<NcolB;j++)
         {System.out.print(" "+(matrizC[i][j])+"\t");}
     System.out.print("\n");
     }         
  }}

No hay comentarios:

Publicar un comentario