Demo entry 6354943

qqq

   

Submitted by qqq on Apr 12, 2017 at 04:49
Language: Java. Code size: 2.8 kB.

package com.lingnan;

public abstract class GenericMatrix <T extends Number>{
	protected abstract T add(T obj1,T obj2);
	
	protected abstract T multiply(T obj1,T obj2);
	
	protected abstract T clear();
	//实现矩阵加法
	public T[][] addMatrix(T[][] matrix1,T[][] matrix2){
		//检测矩阵是否合法
		if((matrix1.length!=matrix2.length)||(matrix1[0].length!=matrix2[0].length)){
			throw new RuntimeException("不符合矩阵加法的条件");
		}
		T[][] result=(T[][])new Number[matrix1.length][matrix1[0].length];
		for(int i=0;i<result.length;i++)
			for(int j=0;j<result[0].length;j++){
				result[i][j]=add(matrix1[i][j],matrix2[i][j]);
			}
		return result;
	}
	//实现矩阵乘法
	public T[][] multiplyMatrix(T[][] matrix1,T[][] matrix2){
		//检测矩阵是否合法
		if(matrix1[0].length!=matrix2.length){
			throw new RuntimeException("不符合矩阵乘法的条件");
		}
		T[][] result=(T[][])new Number[matrix1.length][matrix2[0].length];
		for(int i=0;i<result.length;i++)
			for(int j=0;j<result[0].length;j++){
				result[i][j]=clear();
				for(int k=0;k<matrix1[0].length;k++){
					result[i][j]=add(result[i][j],multiply(matrix1[i][k],matrix2[k][j]));
				}
			}
		return result;
	}
	//重载矩阵乘法
	public T[][] multiplyMatrix(T[][] matrix1,T[] matrix2){
		//检测矩阵是否合法
		if(matrix1.length!=matrix2.length){
			throw new RuntimeException("不符合矩阵乘法的条件");
		}
		T[][] result=(T[][])new Number[matrix1.length][matrix2.length];
		for(int i=0;i<result.length;i++)
			for(int j=0;j<result[0].length;j++){
				result[i][j]=clear();
				result[i][j]=multiply(matrix1[i][0],matrix2[j]);
				
			}
		return result;
	}
	//控制输出格式
	public static void outputResult(Number[][] m1,Number[][] m2,Number[][] m3,char operator){
		for(int i=0;i<m1.length;i++){
			
			for(int j=0;j<m1[0].length;j++)
				System.out.print(" "+m1[i][j]);
			if(i==m1.length/2)
				System.out.print(" "+operator+" ");
			else
				System.out.print("   ");
			
			for(int j=0;j<m2[0].length;j++)
				System.out.print(" "+m2[i][j]);
			if(i==m1.length/2)
				System.out.print(" = ");
			else
				System.out.print("   ");
			
			for(int j=0;j<m3[0].length;j++)
				System.out.print(m3[i][j]+" ");
			System.out.println();
		}
	}
	//重载输出格式
	public static void outputResult(Number[][] m1,Number[] m2,Number[][] m3,char operator){
		for(int i=0;i<m1.length;i++){
			
			for(int j=0;j<m1[0].length;j++)
				System.out.print(" "+m1[i][j]);
			if(i==m1.length/2)
				System.out.print(" "+operator+" ");
			else
				System.out.print("   ");
			
			for(int j=0;j<m2.length;j++)
				if(i==m1.length/2)
					System.out.print(" "+m2[j]);
				else
					System.out.print("  ");
			if(i==m1.length/2)
				System.out.print(" = ");
			else
				System.out.print("   ");
			
			for(int j=0;j<m3[0].length;j++)
					System.out.print(m3[i][j]+" ");
			System.out.println();
		}
	}
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).