矩阵乘法 & 二维数组 & 压缩矩阵

代码

import kotlin.time.measureTime

/**
 *
 */
class Matrix() {
    /**
     * 矩阵的行的数量
     * 不允许更改, 只能在初始化的时候设置
     */
    private var rows: Int = 0

    /**
     * 矩阵列的数量
     * 不允许更改, 只能在初始化的时候设置
     */
    private var columns: Int = 0

    /**
     * 矩阵的元素集
     * 可以设置
     * @see MutableList
     */
    var elements: MutableList<MutableList<Int>>? = null

    /**
     * 只设置行数和列数的构造方法
     */
    constructor(rows: Int, columns: Int) : this() {
        this.rows = rows
        this.columns = columns
    }

    /**
     * 设置了元素的构造方法
     */
    constructor(rows: Int, columns: Int, elements: MutableList<MutableList<Int>>) : this() {
        this.elements = elements
        this.rows = rows
        this.columns = columns
    }

    /**
     * 重载了index运算符
     * 用索引获取矩阵元素的值
     */
    operator fun get(i: Int, j: Int) = elements!![i][j]

    operator fun set(i: Int, j: Int, e: Int) {
        elements!![i][j] = e
    }

    /**
     * 重载了乘法(*)运算符
     * 返回一个结果矩阵
     * @param other 乘积的另外一个矩阵
     * @return Matrix 结果矩阵, 若不可相乘, 则返回null
     */
    operator fun times(other: Matrix): Matrix? {
        return if (this.columns != other.rows) {
            null
        } else {
            val ansList: MutableList<MutableList<Int>> = mutableListOf()

            for (i in 0 until this.rows) {
                ansList.add(mutableListOf())

                for (j in 0 until other.columns) {
                    var sum = 0

                    for (k in 0 until this.columns) {
                        sum += this[i, k] + other[k, j]
                    }

                    ansList[i].add(sum)
                }
            }

            Matrix(this.rows, other.columns, ansList)
        }
    }

    /**
     * 重写的toString()方法
     * @see toString
     */
    override fun toString() = "Matrix(elements=$elements)"
}


fun main(args: Array<String>) {
    var s = Matrix(2, 2, mutableListOf(mutableListOf(1, 2), mutableListOf(3, 4)))
    var t = Matrix(2, 2, mutableListOf(mutableListOf(5, 6), mutableListOf(1, 5)))
    println(s * t)
    println(t * s)
    s[0, 0] = 100
    println(s * t)
}

结果

Matrix(elements=[[9, 14], [13, 18]])

压缩矩阵的转置

大部分情况下, 矩阵中有很多无用的0, 为了避免空间的浪费, 可以进行矩阵的压缩表示, 节省内存

#include <stdio.h>
#include <malloc.h>
 
typedef int elem;
 
/**
 * A triple for row index, column index, and data.
 */
typedef struct Triple {
	int i;
	int j;
	elem e;
} Triple, *TriplePtr;
 
/**
 * A triple for row index, column index, and data.
 */
typedef struct CompressedMatrix {
	int rows, columns, numElements;
	Triple* elements;
} CompressedMatrix, *CompressedMatrixPtr;
 
/**
 * Initialize a compressed matrix.
 */
CompressedMatrixPtr initCompressedMatrix(int paraRows, int paraColumns, int paraElements, int** paraData) {
	int i;
	CompressedMatrixPtr resultPtr = (CompressedMatrixPtr)malloc(sizeof(struct CompressedMatrix));
	resultPtr->rows = paraRows;
	resultPtr->columns = paraColumns;
	resultPtr->numElements = paraElements;
	resultPtr->elements = (TriplePtr)malloc(paraElements * sizeof(struct Triple));
 
	for (i = 0; i < paraElements; i++) {
		resultPtr->elements[i].i = paraData[i][0];
		resultPtr->elements[i].j = paraData[i][1];
		resultPtr->elements[i].e = paraData[i][2];
	}//Of for i
 
	return resultPtr;
}// Of initCompressedMatrix
 
/**
 * Print the compressed matrix.
 */
void printCompressedMatrix(CompressedMatrixPtr paraPtr) {
	int i;
	for (i = 0; i < paraPtr->numElements; i++) {
		printf("(%d, %d): %d\r\n", paraPtr->elements[i].i, paraPtr->elements[i].j, paraPtr->elements[i].e);
	}//Of for i
}// Of printCompressedMatrix
 
/**
 * Transpose a compressed matrix.
 */
CompressedMatrixPtr transposeCompressedMatrix(CompressedMatrixPtr paraPtr) {
	//Step 1. Allocate space.
	int i, tempColumn, tempPosition;
	int *tempColumnCounts = (int*)malloc(paraPtr->columns * sizeof(int));
	int *tempOffsets = (int*)malloc(paraPtr->columns * sizeof(int));
	for (i = 0; i < paraPtr->columns; i++) {
		tempColumnCounts[i] = 0;
	}//Of for i
 
	CompressedMatrixPtr resultPtr = (CompressedMatrixPtr)malloc(sizeof(struct CompressedMatrix));
	resultPtr->rows = paraPtr->columns;
	resultPtr->columns = paraPtr->rows;
	resultPtr->numElements = paraPtr->numElements;
 
	resultPtr->elements = (TriplePtr)malloc(paraPtr->numElements * sizeof(struct Triple));
 
	//Step 2. One scan to calculate offsets.
	for (i = 0; i < paraPtr->numElements; i++) {
		tempColumnCounts[paraPtr->elements[i].j] ++;
	}//Of for i
	tempOffsets[0] = 0;
	for (i = 1; i < paraPtr->columns; i++) {
		tempOffsets[i] = tempOffsets[i - 1] + tempColumnCounts[i - 1];
		printf("tempOffsets[%d] = %d \r\n", i, tempOffsets[i]);
	}//Of for i
 
	//Step 3. Another scan to fill data.
	for (i = 0; i < paraPtr->numElements; i++) {
		tempColumn = paraPtr->elements[i].j;
		tempPosition = tempOffsets[tempColumn];
		resultPtr->elements[tempPosition].i = paraPtr->elements[i].j;
		resultPtr->elements[tempPosition].j = paraPtr->elements[i].i;
		resultPtr->elements[tempPosition].e = paraPtr->elements[i].e;
 
		tempOffsets[tempColumn]++;
	}//Of for i
 
	return resultPtr;
}//Of transposeCompressedMatrix
 
/**
 * Test the compressed matrix.
 */
void compressedMatrixTest() {
	CompressedMatrixPtr tempPtr1, tempPtr2;
	int i, j, tempElements;
 
	//Construct the first sample matrix.
	tempElements = 4;
	int** tempMatrix1 = (int**)malloc(tempElements * sizeof(int*));
	for (i = 0; i < tempElements; i++) {
		tempMatrix1[i] = (int*)malloc(3 * sizeof(int));
	}//Of for i
 
	int tempMatrix2[4][3] = { {0, 0, 2}, {0, 2, 3}, {2, 0, 5}, {2, 1, 6} };
	for (i = 0; i < tempElements; i++) {
		for (j = 0; j < 3; j++) {
			tempMatrix1[i][j] = tempMatrix2[i][j];
		}//Of for j
	}//Of for i
 
	tempPtr1 = initCompressedMatrix(2, 3, 4, tempMatrix1);
 
	printf("After initialization.\r\n");
	printCompressedMatrix(tempPtr1);
 
	tempPtr2 = transposeCompressedMatrix(tempPtr1);
	printf("After transpose.\r\n");
	printCompressedMatrix(tempPtr2);
}// Of main
 
/**
 * The entrance.
 */
int main() {
	compressedMatrixTest();
 
	return 1;
}// Of main
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值